英文:
Why Pattern not returning true
问题
The second regex pattern you provided appears to have an issue with extra spaces. Here's the corrected version:
Pattern patternForBin = Pattern.compile("^(0b|0B|1)[0-1]*(b|B)$");
The issue with the original pattern is that it used the | operator with spaces on both sides, which can be interpreted incorrectly. The corrected pattern uses | to match either "0b" or "0B" or "1", and then proceeds to match the binary digits and "b" or "B" at the end. This pattern should work as intended.
英文:
Regex formed with rules:
1.Start with 1
2.End with b or B.
For Eg. 101b
OR
- Can start with 0b or 0B
- Then will have 1
For Eg. 0b1000101
Pattern patternForBin=Pattern.compile("(^(1)[0-1]*(b|B)$)");
This regex returns true with "101b" but when I tried same with |
Pattern patternForBin=Pattern.compile("(^(0b|B)1[0-1]*) | (^(1)[0-1]*(b|B)$)");
Why pattern didn't match?
答案1
得分: 2
在正则表达式中有空格字符(' ')。在正则表达式中,空白字符不会被忽略。正则表达式试图匹配表达式中的空格,所以它不匹配。
英文:
There are space characters (' ') in the regex. In regex, whitespace is not ignored. The regular expression is trying to match the spaces in the expression so it doesn't match.
答案2
得分: 2
Pattern patternForBin = Pattern.compile("^(0b|B)1[0-1]|^(1)[0-1](b|B)$");
FullCode:
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);
Output: true
英文:
Remove space from regex from both side of |, it a valid character for match inside regex
Pattern patternForBin=Pattern.compile("(^(0b|B)1[0-1]*)|(^(1)[0-1]*(b|B)$)");
FullCode:
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);
Output: true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论