Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I must specify whole string in Java regular expression? [duplicate]

Tags:

java

regex

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
like image 708
spirit Avatar asked Jul 04 '16 11:07

spirit


People also ask

How do you check if a string matches a regex in Java?

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).

How do you repeat a pattern in regex?

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.


1 Answers

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

like image 143
Chris Jester-Young Avatar answered Oct 04 '22 00:10

Chris Jester-Young