RegEx: Match any non-empty string, including line breaks

Viewed 182

I'd like to match any non-empty, multi-line string fully. In PHP-Flavour I'd do it with the \X token, which matches any characters including line breaks. Unfortunately, I need to use Java, where the \X token does not work.

Example of a string I would like to match fully (Match 1):

This is a 
multi-line
string with some charakters like $ and / and ´
to match fully.
1 Answers

In Java regex flavor, \X is really not supported, and any code point pattern can be expressed with "any non-diacritic char + any zero or more diacritics", i.e. \P{M}\p{M}*+.

However, you just want to match any non-empty string. You can use

(?s)\A.+\z

pattern. Details:

  • (?s) - an embedded flag option (equal to Pattern.DOTALL in Java) that makes . match any chars including line break chars
  • \A - string start anchor
  • .+ - any one or more chars, as many as possible (it is a greedy dot pattern)
  • \z - the very end of string.

To match any non-empty and non-blank string, you'd use

(?s)\A\s*\S.*\z

The \s*\S.* part matches zero or more whitespaces (\s*), then any non-whitespace char (\S) and then .* matches the rest of the string.

Related