While writing this answer, I had to match exclusively on linebreaks instead of using the s
-flag (dotall
- dot matches linebreaks).
The sites usually used to test regular expressions behave differently when trying to match on \n
or \r\n
.
I noticed
Regex101 matches linebreaks only on
\n
(example - delete\r
and it matches)RegExr matches linebreaks neither on
\n
nor on\r\n
and I can't find something to make it match a linebreak, except for them
-flag and\s
(example)Debuggex behaves even more different:
in this example it matches only on\r\n
, while
here it only matches on\n
, with the same flags and engine specified
I'm fully aware of the m
-flag (multiline - makes ^
match the start and $
the end of a line), but sometimes this is not an option. Same with \s
, as it matches tabs and spaces, too.
My thought to use the unicode newline character (\u0085
) wasn't successful, so:
- Is there a failsafe way to integrate the match on a linebreak (preferably regardless of the language used) into a regular expression?
- Why do the above mentioned sites behave differently (especially Debuggex, matching once only on
\n
and once only on\r\n
)?
[\r\n]+
- or something like this\r?\n
to match both\r\n
and\n
line termination sequences. It doesn't work for the old\r
Mac syntax, but that one is pretty rare these days.DOTALL
. "The regular expression.
matches any character except a line terminator unless theDOTALL
flag is specified.", see java.util.regex. Or see Regex: Make Dot Match Newline? - Salesforce SE. Or in Python:regex = re.compile(r'^\s*(#.*).*$', re.DOTALL, re.MULTILINE)
which makes a.
eat line breaks. If you cannot do that for every dot in the Regex, you need\r\n
where it is needed.