Take the 2-minute tour ×

How to preg_match for an null (empty) string??

I need something like:

/([0-9]|[NULL STRING])/
share|improve this question
add comment

4 Answers

up vote 31 down vote accepted

You can use ^ to match beginning-of-line, and $ to match end-of-line, thus the regular expression ^$ would match an empty line/string.

Your specific example (a line/string containing a single digit or being empty) would easiest be achieved with ^[0-9]?$.

share|improve this answer
Or ^\d?$ - somehow I like \d than [0-9], sorry :) –  Amarghosh Nov 27 '09 at 16:32
@Amarghosh: I too prefer \d, especially as it is a lot easier/shorter to type. Though, for regular expression beginners, I like to stick with the basics when giving examples as fancy stuff like \d doesn't work in all regular expression flavors. –  Mikael Auno Nov 27 '09 at 17:15
...and \d doesn't mean the same thing as [0-9] in some regex flavors. For instance, in .NET, \d matches ٣ (Arabic numeral 3). –  Tim Pietzcker Nov 27 '09 at 20:45
add comment

With PHP's regex you can just say:


It may be usefull...

share|improve this answer
add comment

You can also match a null character with \0. Is that what you meant by [NULL STRING]? That expression could be /([0-9]|\0)/.

share|improve this answer
add comment

I had to do this, in java, for the last 4 for a CC number. The field is optional so it could either be empty, or 4 digits. My solution is:


The is passing this a null in the typical java fashion results in a null pointer exception:

String myString = null;
last4Pattern.matcher(myString).matches(); //Null in this case.

However, I feel that it is more of a Java implementation problem.

share|improve this answer
add comment

Your Answer


