Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression to match exactly 5 digits

testing= testing.match(/(\d{5})/g); 

I'm reading a full html into variable. From the variable, want to grab out all numbers with the pattern of exactly 5 digits. No need to care of whether before/after this digit having other type of words. Just want to make sure whatever that is 5 digit numbers been grabbed out.

However, when I apply it, it not only pull out number with exactly 5 digit, number with more than 5 digits also retrieved...

I had tried putting ^ in front and $ behind, but it making result come out as null.

like image 630
i need help Avatar asked Feb 12 '11 01:02

i need help


People also ask

How does regex Match 5 digits?

match(/(\d{5})/g);

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.

Which regex matches one or more digits?

Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.

How many numbers are possible with 5 digits?

How Many 5-Digit Numbers are there? There are 90,000 five-digit numbers including the smallest five-digit number which is 10,000 and the largest five-digit number which is 99,999.


1 Answers

I am reading a text file and want to use regex below to pull out numbers with exactly 5 digit, ignoring alphabets.

Try this...

var str = 'f 34 545 323 12345 54321 123456',     matches = str.match(/\b\d{5}\b/g);  console.log(matches); // ["12345", "54321"] 

jsFiddle.

The word boundary \b is your friend here.

Update

My regex will get a number like this 12345, but not like a12345. The other answers provide great regexes if you require the latter.

like image 53
alex Avatar answered Sep 24 '22 10:09

alex