Regex for a field containing 13 digits?

Do I need a regular expression to validate a field that is empty or equal to 13 digits?

Regards, Francis P.

+4
source share
1 answer

Try it ( see also at rubular.com ):

^(\d{13})?$

Explanation:

  • ^ , $ - beginning and end of string bindings
  • \d is a character class for numbers
  • {13} - exact final repetition
  • ? is "zero or one", that is, optional

References


By definition, empty

The above pattern matches a 13-digit string or an empty string, that is, a string whose length is zero. If "empty" means "empty", that is, it probably does not contain anything other than whitespace, then you can use \s* as an alternation. Striping is just how you compare this|that . \s is the character class for whitespace, * is the "zero or more" repetition.

So maybe something like this ( see also at rubular.com ):

^(\d{13}|\s*)?$

References

Related question

+14
source

Source: https://habr.com/ru/post/1313511/


All Articles