3

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!

4 Answers 4

6

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Aah I see! This makes sense as earlier it matches begin and end of a string even though I hadn't added ^ and $! Thanks!
Why is this the behaviour? If I wanted it to match the whole string I would put start and end markers on it myself. Is there a reason I'm not seeing here?
1

You must add either * or + to your regexp:

str.matches("[^=]+=[^=]+")

This is needed, because string.matches() is anchored by default. This is equivalent to ^[^=]+=[^=]+$ and means that it must match the whole string and not only a part of it.

Comments

1

You are just matching single character before and after =. Now, since String#matches tries to match the complete string with the given Pattern, so you need to ensure that you cover complete string in it. Obviously, your string does contain many characters before and after =.

So, to specify this, you need to use a quantifier, here: -

  • + to match one or more characters
  • * to match zero or more characters

So, you would need to change your regex to: -

System.out.println(str + " - " + str.matches("[^=]+=[^=]+"))

Comments

1

The problem is that String.matches() does not search for a matching subsequence, but instead tries to match the complete string against your pattern.

For your purpose, you need Matcher.find(): http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#find()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.