regular expression to match exactly 5 digits regular expression to match exactly 5 digits javascript javascript

regular expression to match exactly 5 digits


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.


My test string for the following:

testing='12345,abc,123,54321,ab15234,123456,52341';

If I understand your question, you'd want ["12345", "54321", "15234", "52341"].

If JS engines supported regexp lookbehinds, you could do:

testing.match(/(?<!\d)\d{5}(?!\d)/g)

Since it doesn't currently, you could:

testing.match(/(?:^|\D)(\d{5})(?!\d)/g)

and remove the leading non-digit from appropriate results, or:

pentadigit=/(?:^|\D)(\d{5})(?!\d)/g;result = [];while (( match = pentadigit.exec(testing) )) {    result.push(match[1]);}

Note that for IE, it seems you need to use a RegExp stored in a variable rather than a literal regexp in the while loop, otherwise you'll get an infinite loop.


This should work:

<script type="text/javascript">var testing='this is d23553 test 32533\n31203 not 333';var r = new RegExp(/(?:^|[^\d])(\d{5})(?:$|[^\d])/mg);var matches = [];while ((match = r.exec(testing))) matches.push(match[1]);alert('Found: '+matches.join(', '));</script>