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
Variant 1: String matches() This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str. matches(regex) yields exactly the same result as the expression Pattern. matches(regex, str).
A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.
matches
always matches the whole input string. If you want to allow substrings to match, use find
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With