简体   繁体   English

正则表达式在特定单词后查找 href

[英]Regex find href after certain word

<a href="">ABCD</a>
<a href="text1">ABCD</a>
<a href="text2">ABCD</a>

I need js regex to find first href after "ABCD", "text1" not "text2".我需要js regex在“ABCD”、“text1”而不是“text2”之后找到第一个href。

You are not very specific but this你不是很具体,但是这个

>\w+<[^h]*href="([^"]*)"

should be close to what you are looking for.应该接近你正在寻找的。

Note: You want to get not the whole match but the first capture group.注意:您想要的不是整个匹配,而是第一个捕获组。

Live demo (click Tools -> List to check the groups)现场演示(点击工具 -> 列表查看组)

At the suggestion of @G0dsquad I have posted a formal answer.在@G0dsquad 的建议下,我发布了正式答案。 The regex pattern I used below is:我在下面使用的正则表达式模式是:

^.*?ABCD.*?href="(.*?)".*$

 var input = "<a href=\\"\\">ABCD</a><a href=\\"text1\\">ABCD</a><a href=\\"text2\\">ABCD</a>"; var regex = /^.*?ABCD.*?href="(.*?)".*$/g; var match = regex.exec(input); console.log(match[1]);

Note that I stripped away the line breaks in the input to cram everything into a single line.请注意,我去掉了输入中的换行符,将所有内容都塞进了一行。 But adding newline characters should not change the behavior of the regex.但是添加换行符不应改变正则表达式的行为。 Also note that Regex101, while a very useful tool, appears to apply the regex to each individual line, which will not be your use case.另请注意,Regex101 虽然是一个非常有用的工具,但似乎将正则表达式应用于每一行,这不是您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM