Hi I'm trying to find a regular expression where a binary number has no ones and zeros follow each other directly. This is the regular expression I have:
public static boolean isBin2(String bin2) {
Pattern regexBinary2 = Pattern.compile("(01*01)*");
Matcher matcher = regexBinary2.matcher(bin2);
return matcher.matches();
}
This is the String I'm using for my tests: "10101010"
The expression should check like this:
10101010 --> is allowed
10010101 --> is not allowed
But this expression always returns false even when the binary number is allowed and I can't find the cause of it. Would be nice if you could help me.
Here is a regular expression that doesn't use look around:
^0?(10)*1?$
It says that valid input starts with an optional 0, is followed by zero or more sequences of 10
, and optionally has one more 1 at the end.
This will also match empty input. If an empty input should be rejected, then add a \b
:
^\b0?(10)*1?$
Make sure to escape the backslash when placing this in a string literal:
Pattern regexBinary2 = Pattern.compile("^\\b0?(10)*1?$");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.