Regular Expressions- Match Anything

Walker picture Walker · Jul 15, 2011 · Viewed 619.1k times · Source

How do I make an expression to match absolutely anything (including whitespaces)?
Example:

Regex: I bought _____ sheep.

Matches: I bought sheep. I bought a sheep. I bought five sheep.

I tried using (.*), but that doesn't seem to be working.

Answer

Tim Pietzcker picture Tim Pietzcker · Jul 15, 2011

Normally the dot matches any character except newlines.

So if .* isn't working, set the "dot matches newlines, too" option (or use (?s).*).

If you're using JavaScript, which doesn't have a "dotall" option, try [\s\S]*. This means "match any number of characters that are either whitespace or non-whitespace" - effectively "match any string".

Another option that only works for JavaScript (and is not recognized by any other regex flavor) is [^]* which also matches any string. But [\s\S]* seems to be more widely used, perhaps because it's more portable.