Ernelli
Ernelli

Reputation: 4040

Java regex basic usage problem

The following code works:

String str= "test with foo hoo";
Pattern pattern = Pattern.compile("foo");
Matcher matcher = pattern.matcher(str);

if(matcher.find()) { ... }

But this example does not:

if(Pattern.matches("foo", str)) { ... }

And neither this version:

if(str.matches("foo")) { ... }

In the real code, str is a chunk of text with multiple lines if that is treated differently by the matcher, also in the real code, replace will be used to replace a string of text.

Anyway, it is strange that it works in the first version but not the other two versions.

Edit

Ok, I realise that the behaviour is the same in the first example if if(matcher.matches()) { ... } is used instead of matcher.find. I still cannot make it work for multiline input but I stick to the Pattern.compile/Pattern.matcher solution anyway.

Upvotes: 1

Views: 425

Answers (2)

polygenelubricants
polygenelubricants

Reputation: 383726

In Java, String.matches delegates to Pattern.matches which in turn delegates to Matcher.matches, which checks if a regex matches the entire string.

From the java.util.regex.Matcher API:

Once created, a matcher can be used to perform three different kinds of match operations:

  • The matches method attempts to match the entire input sequence against the pattern.
  • The lookingAt method attempts to match the input sequence, starting at the beginning, against the pattern.
  • The find method scans the input sequence looking for the next subsequence that matches the pattern.

To find if a substring matches pattern, you can:

  • Matcher.find() the pattern within the string
  • Check if the entire string matches .*pattern.*

Related questions

On matches() matching whole string:

On hitEnd() for partial matching:

On multiline vs singleline/Pattern.DOTALL mode:

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838066

Your last couple of examples fail because matches adds an implicit start and end anchor to your regular expression. In other words, it must be an exact match of the entire string, not a partial match.

You can work around this by using .*foo.* instead. Using Matcher.find is more flexible solution though, so I'd recommend sticking with that.

Upvotes: 3

Related Questions