0

I'm using the following Regular Expression: [a-zA-Z]+ to detect if a string contains text but this fails in Java 1.7. It does work in Notepad++. What am I missing?

String message = "123 foo 567";
if (message.matches("[a-zA-Z]+")) {
    System.out.println("Success");
} else
    System.out.println("Fail");

"foo" --> Success
"123 foo" --> Fail
"foo 456" --> fail
ckielstra
  • 93
  • 1
  • 4
  • This check if the string _matches_ the regular expression, not if it contains instances of it. See http://stackoverflow.com/q/15130309/1348195 – Benjamin Gruenbaum Feb 23 '14 at 23:27

2 Answers2

2

From the Java API Specification on Matcher.matches():

Returns:
true if, and only if, the entire region sequence matches this matcher's pattern

(emphasis are mine). That is as if you were wrapping your expression in ^...$ in Notepad++.

Use Matcher.find() instead.

Johannes H.
  • 5,875
  • 1
  • 20
  • 40
  • Thanks for the pointer. It would have been nice when this subtlety was mentioned in the documentation for String.matches as well. – ckielstra Feb 24 '14 at 09:42
  • Yeah, they kinda missed that. Internally `String.matches` is using `Matcher.matches()`, if you know that you can make the connection... BUt most people won'T read the sourcecode just to get this. – Johannes H. Feb 24 '14 at 11:53
1

Another way to get String.matches work on partial strings instead of the whole string you can add a .* at start and end of the matching string to undo the effect of ^...$, like in: .*[a-zA-Z]+.*

ckielstra
  • 93
  • 1
  • 4