首页 > 解决方案 > 正则表达式匹配字符串中的所有href,除非包含一个单词

问题描述

我正在尝试匹配href字符串中的所有内容,但是当 href 包含特定文本时排除(我相信使用负前瞻),例如login,例如:

const str = `This is some a string <a href="http://www.google.com">google</a> and this is another that should not be found <a href="https://www.google.com/login">login</a>`

const match = str.match(/href="(.*?)"/g)

console.log(match)

这匹配所有href,但不考虑排除login在一个中。我尝试了一些不同的变化,但真的没有得到任何地方。任何帮助将不胜感激!

标签: javascriptregex

解决方案


你可以使用这个正则表达式,它在引用之前做一个负面的观察,

href="(.*?)(?<!login)"

演示,

https://regex101.com/r/15DwZE/1

编辑1:正如第四只鸟指出的那样,上面的正则表达式可能无法正常工作,而不是想出一个复杂的正则表达式来覆盖url中登录出现的所有可能性被拒绝,这是一个javascript解决方案。

var myString = 'This is some a string <a href="http://www.google.com">google</a> and this is another that should not be found <a href="https://www.google.com/login">login</a>';
var myRegexp = /href="(.*?)"/g;
match = myRegexp.exec(myString);
while (match != null) {
    if (match[1].indexOf('login') == -1) {
        console.log(match[1]);
    }
  match = myRegexp.exec(myString);
}


推荐阅读