What is a regex to match ONLY an empty string?

There are lots of posts about regexs to match a potentially empty string, but I couldn't readily find any which provided a regex which only matched an empty string.

I know that ^ will match the beginning of any line and $ will match the end of any line as well as the end of the string. As such, /^$/ matches far more than the empty string such as "\n", "foobar\n\n", etc.

I would have thought, though, that /\A\Z/ would match just the empty string, since \A matches the beginning of the string and \Z matches the end of the string. However, my testing shows that /\A\Z/ will also match "\n". Why is that?


Solution 1:

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.

Solution 2:

It's as simple as the following. Many of the other answers aren't understood by the RE2 dialect used by C and golang.

^$