Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for just 7 digits and 9 digits

Tags:

regex

I was searching for regular expression for just 7 digits and another for just 9 digits, all I found was for [0-7] and [0-9], not exact 7 and 9 digits - no shorter no longer-

How can I find those ?

like image 842
Noon Avatar asked Nov 03 '12 16:11

Noon


People also ask

What is the regular expression for numbers only?

To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.

How do you match a regular expression with digits?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

What is '?' In regular expression?

'?' matches/verifies the zero or single occurrence of the group preceding it. Check Mobile number example. Same goes with '*' . It will check zero or more occurrences of group preceding it.

What is the meaning of 0 9 in a regular expression?

The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9.


2 Answers

Matching seven digits:

^\d{7}$

Matching nine digits:

^\d{9}$

If you want to match either seven or nine digits, use this:

^(\d{7}|\d{9})$

or just this:

^\d{7}(\d{2})?$

Quantifier: The number in curly braces is what we call the quantifier, it determines how many repetitions of the preceding pattern (character or group in parentheses) are matched.

Beginning and end of a string (or line) are denoted with the caret ^ and dollar sign $ respectively.

The pipe character | is used to provide two alternative patterns. It is important to know, that it's precedence is lowest (thanks raina for reminding me), i.e. it will either match everything to its left or to its right, unless constrained with parentheses.

like image 93
phant0m Avatar answered Oct 04 '22 04:10

phant0m


For 7 digits: /^\d{7}$/

For 9 digits: /^\d{9}$/

Stackoverflow was down and I had to "learn" the Regex.

Found it here: Regular expressions in javascript

Learning was better :)

like image 24
MicroWise Avatar answered Oct 04 '22 03:10

MicroWise