Reputation: 73
I need a regular expression to check a field is either empty or is exactly 13 digits?
Regards, Francis P.
Upvotes: 7
Views: 21788
Reputation: 384016
Try this (see also on rubular.com):
^(\d{13})?$
Explanation:
^
, $
are beginning and end of string anchors\d
is the character class for digits{13}
is exact finite repetition?
is "zero-or-one of", i.e. optionalThe above pattern matches a string of 13 digits, or an empty string, i.e. the string whose length is zero. If by "empty" you mean "blank", i.e. possibly containing nothing but whitespace characters, then you can use \s*
as an alternation. Alternation is, simply speaking, how you match this|that
. \s
is the character class for whitespace characters, *
is "zero-or-more of" repetition.
So perhaps something like this (see also on rubular.com):
^(\d{13}|\s*)?$
Upvotes: 21