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.matches function 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:
str.matches("(?s).*[^=]=[^=].*")
(The (?s) ensures the . matches everything.)
Alternatively, you could build a Pattern and use Matcher for greater flexibility. This is what String.matches uses.
final Pattern p = Pattern.compile("[^=]=[^=]");
final Matcher m = p.matcher(str);
return m.find();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With