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")
or str.contains("string")
. My question regards only to Java regular expression.
UPDATE: As stated by @ChrisJester-Young (and @GyroGearless) one of the solutions, if you want to search regex
that is part of a subject string, is to use find()
method like this:
String str = "some strange string with searched symbol";
Matcher m = Pattern.compile("string").matcher(str);
System.out.println(m.find()); //true