正则表达式:排除字符 class
Regular expressions: exclusion in character class
我想匹配 a 和 z 之间的字母范围,x 除外。
我正在为此使用 java.util.regex
API。
我的模式:
[a-z^x] // here a-z shows a range between a to z and ^ means negation
例子
- 如果我输入 "a",它应该匹配。
- 如果我输入 "x",它不应该匹配
您可以重写您的 Pattern
如下:
[a-z&&[^x]]
例子
String[] test = {"abcd", "abcdx"};
// | range
// | | and
// | | | new class excluding "x"
// | | | | adding quantifier for this example
Pattern p = Pattern.compile("[a-z&&[^x]]+");
for (String s: test) {
System.out.println(p.matcher(s).matches());
}
输出
true
false
我想匹配 a 和 z 之间的字母范围,x 除外。
我正在为此使用 java.util.regex
API。
我的模式:
[a-z^x] // here a-z shows a range between a to z and ^ means negation
例子
- 如果我输入 "a",它应该匹配。
- 如果我输入 "x",它不应该匹配
您可以重写您的 Pattern
如下:
[a-z&&[^x]]
例子
String[] test = {"abcd", "abcdx"};
// | range
// | | and
// | | | new class excluding "x"
// | | | | adding quantifier for this example
Pattern p = Pattern.compile("[a-z&&[^x]]+");
for (String s: test) {
System.out.println(p.matcher(s).matches());
}
输出
true
false