Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching an empty string with regex

Tags:

regex

I've seen posts here on stackoverflow that say that the regex ^$ will match an empty string... So it made me think... why not something like this: ^\s+$ - does that not also work? I know it's more typing, but it in my mind, it also makes more sense. I've not used a whole lot of regex before, but it seems like my need for them is becoming greater as the days go by - so I'm taking the hint and attempting to learn.

like image 675
genesys Avatar asked Jul 12 '13 15:07

genesys


1 Answers

^\s+$ - does that not also work?

Not for matching an empty string. In general, X+ means X one or more times. So, \s+ cannot match the empty string - it requires at least one \s in order to match.

                                     ^ \s + $
                                     | |  | |
start of string ---------------------+ |  | |
whitespace character ------------------+  | |
one or more of what precedes -------------+ |
end of string ------------------------------+

Now, X* means X 0 or more times, so ^\s*$ would indeed match an empty string.


^\s+$

enter image description here

^\s*$

enter image description here

like image 67
arshajii Avatar answered Nov 23 '22 09:11

arshajii