Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex not matching properly

Tags:

java

string

regex

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!

like image 640
Hosh Sadiq Avatar asked Jun 27 '26 08:06

Hosh Sadiq


1 Answers

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();
like image 188
kennytm Avatar answered Jun 28 '26 21:06

kennytm