The multiline mode is enabled by the flag
It only affects the behavior of
In the multiline mode they match not only at the beginning and end of the string, but also at start/end of line.
In the example below the text has multiple lines. The pattern
/^\d+/gm takes a number from the beginning of each one:
Without the flag
/.../m only the first number is matched:
That’s because by default a caret
^ only matches at the beginning of the text, and in the multiline mode – at the start of a line.
The regular expression engine moves along the text and looks for a string start
^, when finds – continues to match the rest of the pattern
The dollar sign
$ behaves similarly.
The regular expression
\w+$ finds the last word in every line
/.../m flag the dollar
$ would only match the end of the whole string, so only the very last word would be found.
To find a newline, we can use not only
$, but also the newline character
The first difference is that unlike anchors, the character
\n “consumes” the newline character and adds it to the result.
For instance, here we use it instead of
Here every match is a word plus a newline character.
And one more difference – the newline
\n does not match at the string end. That’s why
Eeyore is not found in the example above.
So, anchors are usually better, they are closer to what we want to get.