Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring is found, but regex fails

Tags:

java

regex

Suppose I have some string, and run the following tests on it:

response.indexOf("</p:panelGrid>");
response.matches(".*</p:panelGrid>.*");

How is it possible that indexOf finds the substring (it does not return -1), but the regular expression in the second test does not match?

I have come across this problem while trying to write a test that checks if taglibs are rendered correctly in JSF with Pax Web. I have not been able to reproduce this behavior outside of this test.

like image 614
Björn Pollex Avatar asked Aug 22 '12 12:08

Björn Pollex


People also ask

How do you check if a string contains a substring regex?

RegExp provides more flexibility. To check for substrings in a string with regex can be done with the test() method of regular expression. This method is much easier to use as it returns a boolean.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What does regex return if no match?

Note: If there is no match, the value None will be returned, instead of the Match Object. The Match object has properties and methods used to retrieve information about the search, and the result: . span() returns a tuple containing the start-, and end positions of the match.

What is \r and \n in regex?

Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.


1 Answers

The . matches everything except for newline characters. You must change your regex string to

"(?s).*</p:panelGrid>.*"

Then it will match always.

like image 197
Marko Topolnik Avatar answered Sep 21 '22 09:09

Marko Topolnik