spirit spirit - 4 months ago 8
Java Question

Why I must specify whole string in Java regular expression?

Suppose, I have a string:

String str = "some strange string with searched symbol";


And I want to search in it some symbols, suppose it will be
"string"
. So we have a following:

str.matches("string"); //false
str.matches(".*string.*"); //true


So, as stated in the title, why I must specify whole string in Java regular expression?

Java documentation says:


public boolean matches(String regex)

Tells whether or not this string matches the given regular expression.


It doesn't says


Tells whether or not this whole string matches the given regular expression.


For example, in the
php
it would be:

$str = "some strange string with searched symbol";
var_dump(preg_match('/string/', $str)); // int(1)
var_dump(preg_match('/.*string.*/', $str)); //int(1)


So, both of the regex's will be
true
.

And I think this is correct, because if I want to test whole string I would do
str.matches("^string$");


PS: Yes, I know that is to search a substring, simpler and faster will be to use
str.indexOf("string")
. My question regards only to Java regular expression.

Answer

matches always matches the whole input string. If you want to allow substrings to match, use find.

Comments