What is a regex to match ONLY an empty string?
I would use a negative lookahead for any character:
^(?![\s\S])
This can only match if the input is totally empty, because the character class will match any character, including any of the various newline characters.
As explained in http://www.regular-expressions.info/anchors.html under the section "Strings Ending with a Line Break", \Z
will generally match before the end of the last newline in strings that end in a newline. If you want to only match the end of the string, you need to use \z
. The exception to this rule is Python.
In other words, to exclusively match an empty string, you need to use /\A\z/
.
It's as simple as the following. Many of the other answers aren't understood by the RE2 dialect used by C and golang.
^$