javascript - 正则表达式匹配字符串中的所有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
在一个中。我尝试了一些不同的变化,但真的没有得到任何地方。任何帮助将不胜感激!
解决方案
你可以使用这个正则表达式,它在引用之前做一个负面的观察,
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);
}
推荐阅读
- php - 如何修复openssl_random_pseudo_bytes(0)中的长度必须大于0?
- groovy - 在 groovy 中获取 java.lang.NullPointerException 而 JSONPATH 查找
- raku - 在 raku REPL 中定义后缀运算符的问题
- r - 根据数据表的列名具有不同线条颜色和轨迹样式的线图
- c# - 有没有办法在 C# 中填充已经打开的网页?
- android - 运行“flutter doctor --android-licenses”时如何修复?
- r - 在 R 中使用表格进行操作
- python - 如何等到工具栏出现在 skribbl.io | Python
- couchdb - Cloudant 对可空字段进行排序
- javascript - MERN 应用程序 - 渲染中的反应状态 - 类型错误:无法读取未定义的属性“用户名”