13

I found this: Regex to match digits of specific length but it talks about Python. I am wanting to be able to get a group of random numbers of specific length. So if I have 167691#15316243 it will match 15316243. I am not sure how to implement this. right now I have new RegExp('[0-9]+', "g"); which matches a group of numbers fine, but now I realized I will have some times when I have more than one group and I only want the group of eight numbers.

Community
  • 1
  • 1
qitch
  • 829
  • 3
  • 12
  • 21

3 Answers3

27
[0-9]+ - Matches one or more numbers
[0-9]{8} - Matches exactly 8 numbers.
[0-9]{8,10} - Matches between 8 and 10 numbers.
[0-9]{8,} - Matches 8 or more numbers.
[0-9]* - Matches zero or more numbers.
[0-9]? - Matches zero or one number.
Nathan
  • 4,017
  • 2
  • 25
  • 20
17

You can specify the length of a matching set using {}.

For example: [0-9]{8}

Which will match any numbers from 0 to 9 with a specific length of 8 characters.

You can also specify a min/max range instead of forcing a specific legnth. So if you wanted a min of 4 and a max of 8 the example would change to: [0-9]{4,8}

Timeout
  • 7,759
  • 26
  • 38
4

Simply put the repetition amount in curly braces:

"167691#15316243".match(/\d{8}/g);

Here's the fiddle: http://jsfiddle.net/3r5vd/


I'd suggest you read this article (scroll down to the section on Limiting Repetition).

Here's a quote:

Modern regex flavors [...] have an additional repetition operator that allows you to specify how many times a token can be repeated. The syntax is {min,max}, where min is a positive integer number indicating the minimum number of matches, and max is an integer equal to or greater than min indicating the maximum number of matches. If the comma is present but max is omitted, the maximum number of matches is infinite. So {0,} is the same as *, and {1,} is the same as +.
Omitting both the comma and max tells the engine to repeat the token exactly min times.

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292