0

I need to match a sub string, and I wonder which one is faster when it comes to matching RegEx?

if ( str.matches(".*hello.*") ) {
  ...
}


Pattern p = Pattern.compile( ".*hello.*" );
Matcher m = p.matcher( str );
if ( m.find() ) {
   ...
}


And if don't need a regEx, should I use 'contains' ?

if ( str.contains("hello") ) {
   ...
}

Thanks.

5
  • Why match in one and find in another? Commented Jun 1, 2014 at 0:32
  • 1
    Please don't use find with a regexp that starts and ends with .* - you don't need the .* with find. And yes, if what you're seeking is just a String, you should absolutely use contains. Commented Jun 1, 2014 at 0:35
  • 1
    RegExe are only needed when looking for a pattern. if you want to find an exact substring there is no need of it, have in mind that RegEx are expensive. Commented Jun 1, 2014 at 0:36
  • If performance is really a concern, why don't you index the data? Commented Jun 1, 2014 at 1:38
  • @DavidWallace I am aware of the .*, it's just an example for the question :) Commented Jun 1, 2014 at 18:40

2 Answers 2

3

Although matches() and using a Matcher are identical (matches() uses a Matcher in its implementation), using a Matcher can be faster if you cache and reuse the compiled Pattern. I did some rough testing and it improved performance (in my case) by 400% - the improvement depends on the regex, but there will always be sone improvement.

Although I haven't tested it, I would expect contains() to outperform any regex approach, because the algorithm is far simpler and you don't need regex for this situation.


Here are the results of 6 ways to test for a String containing a substring, with the target ("http") located at various places within a standard 60 character input:

|------------------------------------------------------------|
| Code tested with "http" in the input  | µsec | µsec | µsec |
| at the following positions:           | start|   mid|absent|
|------------------------------------------------------------|
| input.startsWith("http")              |    6 |    6 |    6 |
|------------------------------------------------------------|
| input.contains("http")                |    2 |   22 |   49 |
|------------------------------------------------------------|
| Pattern p = Pattern.compile("^http.*")|      |      |      |
| p.matcher(input).find()               |   90 |   88 |   86 |
|------------------------------------------------------------|
| Pattern p = Pattern.compile("http.*") |      |      |      |
| p.matcher(input).find()               |   84 |  145 |  181 |
|------------------------------------------------------------|
| input.matches("^http.*")              |  745 |  346 |  340 |
|------------------------------------------------------------|
| input.matches("http.*")               | 1663 | 1229 | 1034 |
|------------------------------------------------------------|

The two-line options are where a static pattern was compiled then reused.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the insight regarding matches and Matcher, I was not aware of that :) Would you recommend to use contains twice to avoid this kind of match: matches("^https*.*$")? One for the 'http' and another for 'https'.
1

They are more or less equivalent if you use m.match() in the second code snippet. String.matches() specs this :

An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str)

this in turn specifies:

An invocation of this convenience method of the form

 Pattern.matches(regex, input);

behaves in exactly the same way as the expression

 Pattern.compile(regex).matcher(input).matches()

If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.

So calling String.matches(String) in itself will not bring performance benefits, but storing a pattern (e.g. as a constant) and reusing it does.


If you use find then matches could be more efficient if the terms don't match early, as find may keep looking. But find and matches don't perform the same function, so comparison of performance is moot.

3 Comments

In other words, the right tool for the right job. "matches" if I just want to know if the pattern is present. "find" if I need to match and get groups.
Almost. matches if you want to match the full string, find if you want to find or detect the presence within the string. Only String.matches forgets the groups, underwater it simply uses Pattern.matcher(String) which does report back the groups, no matter if you call matches() or find() on the resulting Matcher.
So for find, you would almost get the same result for ".*hello.*" as for "hello", main difference being that the first one matches the last hello in the string (".*" reaches to the end, then with traceback "hello.*" is found), just "hello" matches the first hello.

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.