正则表达式,包含字母数字和所有特殊字符(% 除外)
字符串长度必须为 1 到 12。
尝试这种方式(作为正则表达式),但这也允许 %。
[[^=][\w\S][^-]]{1,13}
示例我的输入字符串(itemValue)对于上述模式,应该给出 false:test%t1z
Pattern pattern = Pattern.compile(regexStr);
Matcher matcher = pattern.matcher(itemValue);
if(matcher.matches()){
flag = true;
}
最佳答案
您可以使用以下任一方法:
String regexStr = "[^%]{1,12}"; # If whitespaces are allowed
String regexStr = "[^%\\s]{1,12}"; # If whitespaces are disallowed
请注意,Pattern#matches
需要完整的字符串匹配,因此无需添加像 \A
/\z
这样的 anchor 正则表达式模式。
详细信息
[^%]{1,12}
- 匹配%
之外的任何一到十二个字符[^%\s]{1,12}
- 匹配除%
和空格之外的一到十二个字符
请参阅Java demo :
List<String> strs = Arrays.asList("abc123#67812", "abc123%67812", "abc123#678120");
String regexStr = "[^%\\s]{1,12}";
Pattern pattern = Pattern.compile(regexStr);
for (String itemValue : strs) {
Matcher matcher = pattern.matcher(itemValue);
System.out.println("\"" + itemValue + "\": " + matcher.matches());
}
// => "abc123#67812": true
// "abc123%67812": false
// "abc123#678120": false
关于java - 包含字母数字和所有特殊字符(% 除外)的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67522594/