73

I thought it may be [.\n]+ but that doesn't seem to work?

3 Answers 3

80

The dot cannot be used inside character classes.

See the option Pattern.DOTALL.

Pattern.DOTALL Enables dotall mode. In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators. Dotall mode can also be enabled via the embedded flag expression (?s). (The s is a mnemonic for "single-line" mode, which is what this is called in Perl.)

If you need it on just a portion of the regular expression, you use e.g. [\s\S].

8
  • 2
    Arguably cleaner than [\s\S] would be (?:.|\n). The reason that [.\n] doesn't work is that . isn't special in character classes; specifying the same thing with a literal or, |, works fine. Jul 11, 2010 at 12:09
  • @Antal I don't think (?:.|\n) is as portable since a new line in Windows is \r\n. Maybe (?:.|\n|\r), though now the \r is redundant in Unix.
    – Artefacto
    Jul 11, 2010 at 12:12
  • 1
    Good call. I think the usual solution is \r?\n. Jul 11, 2010 at 12:33
  • 14
    In Java, just do (?s:...) to enable DOTALL mode for a specific section, and stop worrying about stupid OSs. Jul 11, 2010 at 12:58
  • 5
    Or, of course, (?s)...(?-s) to toggle it on then off at those points. Jul 11, 2010 at 13:01
55

Edit: While my original answer is technically correct, as ThorSummoner pointed out, it can be done more efficiently like so

[\s\S]

as compared to (.|\n) or (.|\n|\r)

1
  • 5
    this appears to be very expensive, [\s\S] appears to be a lot kinder on the regex engine anecdotally. May 6, 2016 at 19:57
1

Try this

((.|\n)*)

It matches all characters multiple times

2
  • This cause java.lang.StackOverflowError in java. Is there any workaround in java?
    – SudoCoder
    Jul 22, 2021 at 8:03
  • 1
    @SudoCoder (?s:.*) Dec 22, 2021 at 16:04

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.