Preg Match Empty String

前端 未结 5 1928
不知归路
不知归路 2020-12-30 20:19

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

I need something like:

/([0-9]|[NULL STRING])/
相关标签:
5条回答
  • 2020-12-30 20:30

    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.

    0 讨论(0)
  • 2020-12-30 20:34

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

    0 讨论(0)
  • 2020-12-30 20:38

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

    0 讨论(0)
  • 2020-12-30 20:40

    With PHP's regex you can just say:

    /(\d|)/
    

    It may be usefull...

    0 讨论(0)
  • 2020-12-30 20:41

    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).

    0 讨论(0)
提交回复
热议问题