为什么模式不返回true

huangapple go评论80阅读模式
英文:

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

  1. Can start with 0b or 0B
  2. 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

huangapple
  • 本文由 发表于 2020年8月2日 13:41:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63212763.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定