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.
This should work:
To just match the pattern of 5 digits number anywhere in the string, no matter it is separated by space or not, use this regular expression
(?<!\d)\d{5}(?!\d)
.Sample JavaScript codes:
Here's some quick results.
abc12345xyz (✓)
12345abcd (✓)
abcd12345 (✓)
0000aaaa2 (✖)
a1234a5 (✖)
12345 (✓)
<space>
12345<space>
12345 (✓✓)what is about this?
\D(\d{5})\D
This will do on:
f 23 23453 234 2344 2534 hallo33333 "50000"
23453, 33333 50000
My test string for the following:
If I understand your question, you'd want
["12345", "54321", "15234", "52341"]
.If JS engines supported regexp lookbehinds, you could do:
Since it doesn't currently, you could:
and remove the leading non-digit from appropriate results, or:
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.Try this...
jsFiddle.
The word boundary
\b
is your friend here.Update
My regex will get a number like this
12345
, but not likea12345
. The other answers provide great regexes if you require the latter.