Regular expression bounds for beginning of line (^) and end of line ($) do not work

I have a pattern using ^ and $ to indicate the beginning and end of a line.

Pattern pattern = Pattern.compile( "^Key2 = (.+)$" ); 

and enter the following:

 String text = "Key1 = Twas brillig, and the slithy toves" + "\nKey2 = Did gyre and gimble in the wabe." + "\nKey3 = All mimsy were the borogroves." + "\nKey4 = And the mome raths outgrabe."; 

But pattern.matcher( text ).find() returns false .

Doesn't that work? The template class documentation in the summary states:

  Boundary matchers
 ^ The beginning of a line
 $ The end of a line
+7
java regex
source share
1 answer

By default, these characters correspond to the beginning and end of the entire input sequence.

Further in the same class class documentation (with the addition of a cursor):

By default, the regular expressions ^ and $ ignore linear terminators and match only at the beginning and at the end of the entire input sequence. If the MULTILINE mode is activated, then ^ matches at the beginning of the input and after any line terminator, except at the end of the input. When in MULTILINE mode $ matches only before the line terminator or the end of the input sequence.

This way you can get ^ and $ to work, as they are documented in the pivot table by compiling the template with Pattern.MULTILINE :

 Pattern pattern = Pattern.compile( "^Key2 = (.+)$", Pattern.MULTILINE ); 
+9
source share

All Articles