正则表达式忽略重复的匹配 [英] Regular Expression Ignore duplicate matches

查看:100
本文介绍了正则表达式忽略重复的匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串:

var str = "When Home is on fire go and dance in fire"

我想检查我的字符串是否有单词 home fire

I want check my string have words home and fire

为此,我使用了这个正则表达式:

For doing this i used this Regex :

var words = str.match(/(home)|(fire)/ig)

和这样的输出:

["Home", "fire", "fire"]

如你所见, fire 匹配两次,我想忽略重复的匹配,只显示一次。

As you can see fire matched twice , i want Ignore duplicate matches and only show for once.

感谢您的帮助。

推荐答案

你可以使用这个基于正面的负面前瞻来确保只有当文本中不存在相同的单词时才匹配所需的单词,从而匹配最后一次出现的搜索单词:

You can use this negative lookahead based regex to make sure to match desired word only if same word doesn't exist further in text thus matching last occurrence of the search words:

/(home|fire)(?!.*\1)/ig

输出:

["Home", "fire"]

RegEx演示

这篇关于正则表达式忽略重复的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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