Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for field to contain 13 digits?

Tags:

regex

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

Regards, Francis P.

like image 490
Francis Avatar asked Jun 22 '10 11:06

Francis


People also ask

What does '$' mean in regex?

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

How do you represent digits in regex?

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.

What does ++ mean in regex?

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.


1 Answers

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

  • regular-expressions.info/Anchors, Character Classes, Repetition, Optional

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

  • regular-expressions.info/Alternation

Related question

  • regex, check if a line is blank or not
like image 75
polygenelubricants Avatar answered Nov 06 '22 06:11

polygenelubricants