I need to check if a string has any equals sign on its own. My current regex does not seem to work within Java, even though RegexPal matches it.
My current code is:
String str = "test=tests";
System.out.println(str + " - " + str.matches("[^=]=[^=]"));
In the following test cases the first should be matched, the second shouldn’t:
test=tests // matches t=t
test==tests // doesn't match
Regex Pal does it right, however, Java for some reason returns false for both test cases. Am I going wrong somewhere?
Thanks!
Java’s
String.matchesfunction matches the entire string, instead of just one part. That means, it is roughly equivalent to the regex^[^=]=[^=]$, so both returns false. To build a regex working equivalent to yours, you should use:(The
(?s)ensures the.matches everything.)Alternatively, you could build a Pattern and use Matcher for greater flexibility. This is what String.matches uses.