Reputation:
I want to check multiple lines of text in Java regular expression. But it is always showing false result. Can anyone explain me why?
For example:
11 12
11 12
11 12
For testing those lines, I am using 11 12\r?\n+
. It is working fine in rubular regular expression checker but failing in http://www.regexplanet.com/advanced/java/index.html. Another alternatives I tried was (11 12.\r?\n){3,7}
, which is working fine in rubular regex check but failed in regexplanet Java. Can anyone tell me how can check this type of regular expression having repeating pattern?
Upvotes: 1
Views: 264
Reputation: 336208
11 12\r?\n+
matches 11 12
, followed by an optional carriage return, followed by one or more line feeds (without carriage returns). This is obviously not what you want.
(11 12.\r?\n){3,7}
matches 11 12
, followed by one additional character except newlines, followed by an optional CR and a line feed; all of this is repeated 3 to 7 times. So the dot is wrong here. Use this instead:
(11 12\r?\n){3,7}
Finally, be aware that you usually need to double backslashes in a Java regex because of string escaping rules (although in this particular case, you'll be alright because \r
and \n
happen to work as string escapes, too):
Pattern regex = Pattern.compile("(11 12\r?\n){3,7}"); // works the same as
Pattern regex = Pattern.compile("(11 12\\r?\\n){3,7}");
Upvotes: 2