Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a regex to match ONLY an empty string?

Tags:

string

regex

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?

like image 577
Peter Alfvin Avatar asked Oct 01 '13 22:10

Peter Alfvin


People also ask

Can the empty string be a regex?

regex is not empty string.

What does empty regex match?

An empty regular expression matches everything. > var empty = new RegExp(""); > empty.test("abc") true > empty.test("") true As you probably know, you should only use the RegExp constructor when you are dynamically creating a regular expression.

How do you represent a blank in regex?

Find Whitespace Using Regular Expressions in Java The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.


2 Answers

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.

like image 174
Bohemian Avatar answered Oct 09 '22 05:10

Bohemian


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

^$ 
like image 39
Clay Risser Avatar answered Oct 09 '22 05:10

Clay Risser