如何使用正则表达式匹配字符串中的多个值
嗨,我想突出显示整个金戒指 为此,我正在这样做,
var match = hitem.text[0].match(/<em>(.*?)<\/em>/);
where hitem.text[0]=<em>Gold</em> <em>Ring</em>
但问题是 var match 只获得 Gold,所以我只能突出显示 Gold,我想将其设为一个数组,以便它同时包含 Gold 和 Ring,我该怎么做。 看这里http:http://jsfiddle.net/bhXbh/4/
Hi i want to highlight whole gold ring
for this i am doing as
var match = hitem.text[0].match(/<em>(.*?)<\/em>/);
where hitem.text[0]=<em>Gold</em> <em>Ring</em>
but the problem is var match is getting only Gold so i am able to highlight only Gold, i want to make it an array so that it contains both gold and ring, how can i do it.
look at here http: http://jsfiddle.net/bhXbh/4/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将 global 修饰符添加到您的正则表达式中,如下所示:(
我还添加了“i”,它代表“忽略大小写”,我认为这也是必要的)
http://jsfiddle.net/bhXbh/19/
Add the global modifier to your regexp, like this:
(I also added "i", which stands for "ignore case", I assume that's also necessary)
http://jsfiddle.net/bhXbh/19/
您需要使用正则表达式对象 exec 方法迭代所有匹配项,然后将第一个反向引用保存到数组中。另请注意
/g
标志,它使您的正则表达式成为全局的,也就是说,设置为捕获所有匹配项而不仅仅是第一个匹配项:如果您想组合
匹配项
转换为字符串,当然,您可以执行matches.join(" ");
。其他选项
如果您不介意捕获周围的
标签,您可以执行
var matches = str.match(re);
。如果您只想替换
标签,则可以执行
str.replace(re, "$1");
。You'll want to iterate through all the matches using the regular expression objects
exec
method, and then save the first backref to an array. Note also the/g
flag, which makes your regex global, that is, set up to capture all matches rather than just the first one:If you want to combine the
matches
into a string, of course, you could domatches.join(" ");
.Other options
If you don't mind capturing the surrounding
<em>
tags, you could dovar matches = str.match(re);
.And if you just want to replace the
<em>
tags, you can dostr.replace(re, "$1");
..NET Framework 包含一个特殊的类,您可以将其用于您的目标 - MatchCollection 类。
来自 MSDN 的示例:
.NET Framework is contain a special class which you can use for your goal - MatchCollection class.
Example from MSDN: