I need a regular expression to check a field is either empty or is exactly 13 digits?
Regards, Francis P.
$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.
1.2 Example: Numbers [0-9]+ or \d+ The [...] , known as character class (or bracket list), encloses a list of characters. It matches any SINGLE character in the list. In this example, [0-9] matches any SINGLE character between 0 and 9 (i.e., a digit), where dash ( - ) denotes the range.
A regular expression followed by a plus sign ( + ) matches one or more occurrences of the one-character regular expression. If there is any choice, the first matching string in a line is used. A regular expression followed by a question mark ( ? ) matches zero or one occurrence of the one-character regular expression.
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*)?$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With