I have a pattern using ^ and $ to indicate beginning and end of line.
Pattern pattern = Pattern.compile( "^Key2 = (.+)$" );
and input like this:
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
.
Shouldn't this work? In the Pattern class documentation, the summary specifies:
Boundary matchers ^ The beginning of a line $ The end of a line
The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.
The caret ^ and dollar $ characters have special meaning in a regexp. They are called “anchors”. The caret ^ matches at the beginning of the text, and the dollar $ – at the end. The pattern ^Mary means: “string start and then Mary”.
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
By default, those symbols match the beginning and end of the entire input sequence.
Further down in that same Pattern class documentation (with emphasis added):
By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.
So you can make ^ and $ work as they are documented in summary table by compiling the pattern with Pattern.MULTILINE
:
Pattern pattern = Pattern.compile( "^Key2 = (.+)$", Pattern.MULTILINE );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With