By default, the caret
^ metacharacter matches the position before the first
character in the string.
Given the string "charsequence" applied
against the following patterns:
/^sequence/, the engine will try to match as follows:
Match not Found
The same behaviour will be applied even if the string contains line terminators, such as
\r?\n. Only the position at the start of the string will be matched.
However, if you need to match after every line terminator, you will have to set the multiline mode (
(?m)) within your pattern. By doing so, the caret
^ will match "the beginning of each line", which corresponds to the position at the beginning of the string and the positions immediately after1 the line terminators.
1 In some flavors (Java, PCRE, ...),
^ will not match after the line terminator, if the line terminator is the last in the string.
Some of the regular expression engines that support Multiline modifier:
Pattern pattern = Pattern.compile("(?m)^abc"); Pattern pattern = Pattern.compile("^abc", Pattern.MULTILINE);
var abcRegex = new Regex("(?m)^abc"); var abdRegex = new Regex("^abc", RegexOptions.Multiline)
abc_regex = re.compile("(?m)^abc"); abc_regex = re.compile("^abc", re.MULTILINE);