I need a regular expression to check a field is either empty or is exactly 13 digits?
Regards,
Francis P.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try this (see also on rubular.com):
^(\d{13})?$Explanation:
^,$are beginning and end of string anchors\dis the character class for digits{13}is exact finite repetition?is “zero-or-one of”, i.e. optionalReferences
On the definition of empty
The 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 matchthis|that.\sis 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*)?$References
Related question