6

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?

Yuan Shi
  • 79
  • 1
  • 3
  • Without information about which regex variant you're using, we have no way to tell you exactly why what you tried doesn't work, or what would work instead. You already have multiple answers, so it's really too late to fundamentally change this question. Accept an answer, read the [`regex` tag info page](/tags/regex/info), and if you need more help, ask a new question in accordance with the guidelines there. See also the [help] and perhaps in particular the instructions #or posting a [mcve]. – tripleee Aug 11 '18 at 19:12

3 Answers3

9

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.

The fourth bird
  • 96,715
  • 14
  • 35
  • 52
  • 1
    @tripleee I am reading this as the OP tried `[.\n]*` and that did not work. The OP states that it is clear that the dot does not match a newline. My answer is that the dot is inside a character class and will match only the dot literally or a newline. – The fourth bird Aug 11 '18 at 19:21
3

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.

tripleee
  • 139,311
  • 24
  • 207
  • 268
2

You should rather use

.*\n    -- this one if line can be empty

or

.+\n    -- this one if line must include at least 1 character other that new line

also you should remember that sometimes format of newline can be \r\n (Windows mostly)

m.antkowicz
  • 11,566
  • 12
  • 33