1

The regex String :

"[Ff][uU][Nn][Cc] " 

Matches input:

"fUnC " 

But not:

"func across( a, b )"

And I don't understand why...

I'm testing my expressions here: http://www.regexplanet.com/simple/index.html

I figured out that I (dumbly) needed my regex to be "[Ff][uU][Nn][Cc] .*" for a match.

SOLVED: Don't use the convenience method Pattern.Matches(regex, input) if you are looking for what amounts to a submatch. You should use the Matcher.find() method instead.

avgvstvs
  • 5,556
  • 6
  • 38
  • 69
  • I'm not trying to match the whole string, just testing that the symbol "func " can be detected in the string. – avgvstvs Apr 25 '11 at 00:47
  • Why not use an option to make regexes case insensitive? – Rafe Kettler Apr 25 '11 at 00:49
  • That would be cleaner, but that didn't work. Using the test site (and my own code) the only way to score a match was with `.*` at the end. – avgvstvs Apr 25 '11 at 00:56
  • Java's `Pattern.Matches(regex, input)` apparently tries to match only the entire string. Also, you can't set flags when using Pattern.Matches, so I didn't bother with case-insensitive. – avgvstvs Apr 25 '11 at 00:58
  • are you using Matcher.matches, or Matcher.find? – MeBigFatGuy Apr 25 '11 at 01:04
  • I was using the convenience method `Pattern.Matches(regex, input)` which uses the matches. I learned through this that Matches goes for the whole line, find looks for substrings. Not how I'm used to doing things, but it works now... – avgvstvs Apr 25 '11 at 01:11
  • 1
    As you see, Java’s `matches` method is rather more of an **inconvenience method** than a convenience one. :) You’re hardly the first one to get tripped up by Java’s bizarre redefinition of the word *matches.* There are [plenty of other gotchas](http://stackoverflow.com/questions/5767627/java-regex-helper/5771326#5771326), too. :( – tchrist Apr 25 '11 at 02:30

4 Answers4

4

When I use the regex tester you link to, I see that your regex works with find(), but not with matches(). This is what I would expect -- find() just looks for a regex hit within the target string, while matches() always tries to match the entire string.

njudge
  • 177
  • 1
  • 7
0

"[Ff][uU][Nn][Cc].*" may help...

Vicente Plata
  • 3,320
  • 1
  • 17
  • 26
0

It can be.... it's working fine. But your strings in there and you'll see MATCHES is false, but replaceFirst and ReplaceAll work fine.

If you want MATCHES to be true

add a * at the end

MJB
  • 9,088
  • 6
  • 30
  • 48
0

Have you also tried using the regex tester, ignoring case? There should be a way to turn on case insensitivity in the Java regex matcher.

jefflunt
  • 32,075
  • 7
  • 80
  • 122
  • Not when using the convenience method `Pattern.Matches(regex, input)`. You only can use those flags when doing manual manipulation. – avgvstvs Apr 25 '11 at 01:12