我怎样才能获得正则表达式来查找javascript中的每个匹配项? [英] How can I get a regex to find every match in javascript?

查看:55
本文介绍了我怎样才能获得正则表达式来查找javascript中的每个匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

'121'.match(/[0-9]{2}/gi)

我得到一个包含一个结果的数组:

I get back an array with a single result:

['12']

我该怎么办?让它返回所有结果,即使它们重叠?我希望结果如下:

How can I get it to return all results, even if they overlap? I want the result to be this:

['12', '21']

编辑:或者更好的例子是:

Or a better example would be:

'1234567'.match(...);

应该给我一个数组

[12,
23,
34,
45,
56,
67]

[12, 23, 34, 45, 56, 67]

推荐答案

这只是按你想要的方式工作。

this just won't work in the way you want.

指定模式时 [0-9] {2} match()查找第一次出现的两位数字,然后从该位置继续搜索。因为字符串长度是3,显然它不会找到另一个匹配。

when you specify pattern [0-9]{2}, match() looks up first occurrence of two digit number, then continues search from that place on. as string length is 3, obviously it won't find another match.

你应该使用不同的算法来查找所有两位数字。我建议你使用你的第一场比赛的组合,再做一次跟随正则表达式

you should use different algorithm for finding all two digit numbers. I would suggest using combination of your first match and do one more with following regex

/ [0-9]([0-9] { 2})/ 并组合第一次和第二次运行的集合。

/[0-9]([0-9]{2})/ and combine sets of both first and second run.

这篇关于我怎样才能获得正则表达式来查找javascript中的每个匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆