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 ?
To get a string contains only numbers (0-9) we use a regular expression (/^[0-9]+$/) which allows only numbers.
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.
'?' 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.
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.
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.
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 :)
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