gpt4 book ai didi

java - 字符串中允许的字符的正则表达式返回 false

转载 作者:行者123 更新时间:2023-11-29 03:25:53 25 4
gpt4 key购买 nike

我有一个需求,如下所示

The following special characters are allowed with restrictions in the input string:

. ""(),:;<>@[\]

The restrictions for the special characters are that they must only be used when contained between quotation marks.

对于输入字符串中“:”的简单测试,我编写了如下代码:

private static void testEmailPattern() {
String email = "Test\":\"mail";
String PATTERN = "[\":\"]*";
boolean isValidEmail = email.matches(PATTERN);
System.out.println("Status: " + isValidEmail);
}

但是此代码返回 false 而不是 true。

编辑:阅读评论后,我修改了该代码,但它仍然显示错误。

我修改了我的代码,如下所示:

public class TestFeatures {
private Pattern pattern;
private Matcher matcher;

private static final String PATTERN = "[.*\":\".*]*";

public TestFeatures() {
initEmailPattern();
}

private void initEmailPattern() {
pattern = Pattern.compile(PATTERN);
}

public boolean validate(final String hex) {
matcher = pattern.matcher(hex);
return matcher.matches();
}

/**
* @param args
*/
public static void main(String[] args) {
testEmailPattern();
}

private static void testEmailPattern() {
String email = "Test\":\"mail@mail.com";
TestFeatures thisClazz = new TestFeatures();
boolean isValidEmail = thisClazz.validate(email);
System.out.println("Status: " + isValidEmail);
}
}

最佳答案

您需要积极的前瞻性和积极的回顾。

(.*(?<=")[.\x20(),:;<>@\[\]"](?=").*)+

描述

Regular expression visualization

示例代码

String[] tests = {
"Test:mail",
"Test\":\"mail",
"Test\"ll",
".\".",
"foo\"\"\""
};

String re = "(.*(?<=\")[.\\x20(),:;<>@\\[\\]\"](?=\").*)+";

int len=tests.length;
for(int i=0; i<len;i++) {
System.out.format("Test %d: %s >> %s\n" , i+1, tests[i], tests[i].matches(re));
}

输出

Test 1: Test:mail >> false
Test 2: Test":"mail >> true
Test 3: Test"ll >> false
Test 4: .". >> false
Test 5: foo""" >> true

关于java - 字符串中允许的字符的正则表达式返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21021179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com