Question

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

I need something like:

/([0-9]|[NULL STRING])/
Was it helpful?

Solution

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]?$.

OTHER TIPS

With PHP's regex you can just say:

/(\d|)/

It may be usefull...

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

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:

^\d{4}$|^$

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.

As it is not easy to match an empty string but it is generally possible to match anything that is not an empty string, consider to turn it around and not match the opposite (double negative).
In this example, everything that is not (^) a non-digit (\D) for zero or one time (?):

[^\D]?

(or for specific ascii: [^\x00-\x29\x3a-\xff]?, or unicode: [^\u0000-\u0029\u003a-\uffff]?)

Matches an "" (<empty string>), "0", "1" .. "9", but not a "", (<space>), "A" (non-digit) or "123" (any longer string).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top