Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match new line, why [.\n]* does not work in regex?

Tags:

regex

From my understanding the . match almost all characters in regular expression. Then if I want to match any character including new line why [.\n]* does not work?

like image 411
Yuan Shi Avatar asked Aug 11 '18 18:08

Yuan Shi


2 Answers

Using [.\n]* means a character class which will match either a dot or a newline zero or more times.

Outside the character class the dot has different meaning. You might use a modifier (?s) or specify in the language or tool options to make the dot match a newline.

like image 77
The fourth bird Avatar answered Sep 22 '22 08:09

The fourth bird


Most regular expression dialects define . as any character except newline, either because the implementation typically examines a line at a time (e.g. grep) or because this makes sense for compatibility with existing tools (many modern programming languages etc).

Perl and many languages which reimplement or imitate its style of "modern" regex have an option DOTALL which changes the semantics so that . also matches a newline.

If you don't have that option, try (.|\n)* but this still depends very much on which regex tool you are using; it might not recognize the escape code \n for a newline, either.

like image 33
tripleee Avatar answered Sep 22 '22 08:09

tripleee