Francis
Francis

Reputation: 73

Regex for field to contain 13 digits?

I need a regular expression to check a field is either empty or is exactly 13 digits?

Regards, Francis P.

Upvotes: 7

Views: 21788

Answers (1)

polygenelubricants
polygenelubricants

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

References


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 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*)?$

References

Related question

Upvotes: 21

Related Questions