I thought it may be [.\n]+
but that doesn't seem to work?
3 Answers
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]
.
-
2Arguably 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. Jul 11, 2010 at 12:12 -
1
-
14In Java, just do
(?s:
...)
to enable DOTALL mode for a specific section, and stop worrying about stupid OSs. Jul 11, 2010 at 12:58 -
5Or, of course,
(?s)
...(?-s)
to toggle it on then off at those points. Jul 11, 2010 at 13:01
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)
-
5this appears to be very expensive,
[\s\S]
appears to be a lot kinder on the regex engine anecdotally. May 6, 2016 at 19:57
Try this
((.|\n)*)
It matches all characters multiple times
-
This cause java.lang.StackOverflowError in java. Is there any workaround in java? Jul 22, 2021 at 8:03
-
1