正则表达式精确匹配 5 位数字
testing= testing.match(/(\d{5})/g);
我正在将完整的 html 读入变量中。想要从变量中取出所有具有恰好 5 位数字模式的数字。无需关心该数字前后是否有其他类型的单词。只是想确保 5 位数的数字都被抓出来了。
但是,当我应用它时,它不仅提取出正好 5 位数字的数字,还检索了超过 5 位数字的数字...
我曾尝试将 ^
放在前面,然后将 $ 后面,但它使结果显示为空。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个...
jsFiddle。
单词边界
\b
在这里是你的朋友。更新
我的正则表达式将得到像
12345
这样的数字,但不是像a12345
这样的数字。如果您需要后者,其他答案提供了很好的正则表达式。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.我的测试字符串如下:
如果我理解您的问题,您需要
["12345", "54321", "15234", "52341"]
。如果 JS 引擎支持正则表达式后视,您可以这样做:
因为目前不支持,您可以:
并从适当的结果中删除前导非数字,或者:
请注意,对于 IE,似乎您需要使用 存储在变量中的正则表达式而不是
while
中的文字正则表达式循环,否则你会得到一个无限循环。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.这应该有效:
This should work:
这是怎么回事?
\D(\d{5})\D
这适用于:
f 23 23453 234 2344 2534 Hallo33333 "50000"
23453, 33333 50000
what is about this?
\D(\d{5})\D
This will do on:
f 23 23453 234 2344 2534 hallo33333 "50000"
23453, 33333 50000
要只匹配字符串中任意位置的 5 位数字的模式,无论是否用空格分隔,请使用此正则表达式
(?< ;!\d)\d{5}(?!\d)
。JavaScript 代码示例:
以下是一些快速结果。
abc12345xyz (✓)
12345abcd (✓)
abcd12345 (✓)
0000aaaa2 ( ✖)
a1234a5 (✖)
12345 (✓)
<代码><空格> 12345
<空格>
12345 (✓✓)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 (✓✓)