Reputation: 594
I'm trying to check if each line is equal to "test". When I try to run the following code, I expect the result to be true, because every line is exactly "test". Yet, the result is false.
// Expected outcome:
// "test\ntest\ntest" - should match
// "test\nfoo\ntest" - should not match
// "test\ntesttest\ntest" - should not match
Pattern pattern = Pattern.compile("^test$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher("test\ntest");
System.out.println(matcher.matches()); // result is false
What am I missing here? Why is the result false?
Upvotes: 2
Views: 99
Reputation: 6577
Pattern.MULTILINE
allows your regex to match ^
and $
before and after a line separator, which isn't the default behaviour. The default is to match only on the beginning and end of the input.
However, if you use matches() it tries to match the the regex against the whole input text producing a false, because the input isn't equal to just "test"
.
Although matches() doesn't work, you can use find() to find a subsequence of the input matching the regex. Because ^
and $
match before and after \n
, your pattern finds two subsequences.
But that's just my two cents.
Pattern pattern = Pattern.compile("^test$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher("test\ntest");
System.out.println(matcher.matches()); // prints "false", the whole input doesn't match a single "test"
System.out.println(matcher.find()); // prints "true"
System.out.println(matcher.group()); // prints "test"
System.out.println(matcher.find()); // prints "true"
System.out.println(matcher.group()); // prints "test"
System.out.println(matcher.find()); // prints "false"
Upvotes: 0
Reputation: 626699
With Pattern.compile("^test$", Pattern.MULTILINE)
, you only ask the regex engine to match one single line to be equal to test
. When using Matcher#matches()
, you tell the regex engine to match the full string. Since your string is not equal to test
, you will get false
as the result.
To validate a string that contains lines that are all equal to test
, you may use
Pattern.compile("^test(?:\\Rtest)*$")
In older Java versions, you will need to replace \R
(any line break) with \n
or \r?\n
.
See online demo:
Pattern pattern = Pattern.compile("^test(?:\\Rtest)*$");
Matcher matcher = pattern.matcher("test\ntest");
System.out.println(matcher.matches()); // => true
Upvotes: 1
Reputation: 4521
Since you're using Pattern.MULTILINE
, it's matching against the whole string test\ntest
. But in your regex, you are specifying that the string should consist of only a single instance of test
, since it's surrounded by the start and end anchors.
Upvotes: 2