Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for min 9 numbers

Tags:

regex

I'm trying to make a javascript regex to match:

  • required: 9 or more numbers.
  • optional: dash, forward slash, plus and space characters.
  • forbidden: any other character

So far I have

^[0-9-+\/\s]{9,}$

The only problem with this (I think) is that it counts the non numeric permitted characters along to reach the minimum 9.

How can I amend it so that it only counts the numbers to reach the minimum 9?

like image 709
stef Avatar asked May 15 '13 11:05

stef


People also ask

What does the regex 0 9 ]+ do?

In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.

What does 9 mean in regex?

What does 9 mean in regex? In a regular expression, if you have [a-z] then it matches any lowercase letter. [0-9] matches any digit. So if you have [a-z0-9], then it matches any lowercase letter or digit.

How do you specify a number range in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

What is the regex represent 0 9?

The RegExp [0-9] Expression in JavaScript is used to search any digit which is between the brackets. The character inside the brackets can be a single digit or a span of digits.


2 Answers

If you want to solve this in a single RE (not necessarily recommended, but sometimes useful):

^[-+\/\s]*([0-9][-+\/\s]*){9,}$

Or, if you want the first and last characters to be digits:

^[0-9](^[-+\/\s]*[0-9]){8,}$

That's: a digit, followed by eight or more runs of the optional characters, each ending with a digit.

like image 159
Fred Foo Avatar answered Oct 05 '22 13:10

Fred Foo


You can use lookahead to check if there are 9 or more digits anywhere

^(?=(\D*\d){9,})[\d/+ -]+$
 --------------
         |
         |->match further only if there are 9 or more digits anywhere

OR

^([/+ -]*\d){9,}[/+ -]*$
like image 42
Anirudha Avatar answered Oct 05 '22 13:10

Anirudha