由规则组成的正则表达式:
1。从1开始
2。以b或B结尾。
例如101b
OR
例如0b1000101
Pattern patternForBin=Pattern.compile("(^(1)[0-1]*(b|B)$)");
此正则表达式使用“ 101b”返回true,但是当我用|
尝试相同时
Pattern patternForBin=Pattern.compile("(^(0b|B)1[0-1]*) | (^(1)[0-1]*(b|B)$)");
为什么模式不匹配?
答案 0 :(得分:2)
正则表达式中包含空格字符(' '
)。在正则表达式中,空格不会被忽略。正则表达式试图匹配表达式中的空格,以使其不匹配。
答案 1 :(得分:2)
从|
的两侧删除正则表达式中的空格,它是在正则表达式中匹配的有效字符
Pattern patternForBin=Pattern.compile("(^(0b|B)1[0-1]*)|(^(1)[0-1]*(b|B)$)");
完整代码:
Pattern patternForBin=Pattern.compile("(^(0b|B)1[0-1]*)|(^(1)[0-1]*(b|B)$)");
Matcher matcher = patternForBin.matcher("101b");
boolean matchFound = matcher.find();
System.out.println(matchFound);
输出:true