(http([s]?)://?)(([a-zA-Z0-9]+(.?))+)([a-zA-Z0-9]+((.[a-zA-Z]{2,5}){1,2})((/[a-zA-Z0-9?&=_-~:/?#[]@!$&'()*+,;]*)*)((.[a-zA-Z]{2,5}){0,2}))
这是我的正则表达式,它可以很好地匹配字符串中的链接.但我不希望它选择每个链接.如果链接前面有 ">
或 </a>
,则该链接不应该被数学化.怎么做?
This is my regex which is working well for matching the links in the string. But I don't want it to select every link. If a link has ">
before it, or </a>
after it, that link shouldn't be mathced. How can it be done?
这些应该匹配:
adasdas http://www.stackoverflow.com asdasas
adasdasahttp://www.stackoverflow.com/something asdas
这些不应该匹配:
adasdas<a href="somelink"> http://www.stackoverflow.com </a>asdasas
adasdasa<a href="somelink">http://www.stackoverflow.com/something</a> asdas
为什么我需要这个?:我希望每个链接都可以点击,即使它不在锚标签之间.
Why do I need this?: I want every link to be clickable even if it isn't between anchor tags.
所有关于使用正则表达式解析 html 的免责声明,如果你想使用正则表达式来完成这个任务,这将起作用:
With all the disclaimers about using regex to parse html, if you want to use regex for this task, this will work:
$regex="~<a.*?</a>(*SKIP)(*F)|http://S+~";
参见演示.
这个问题是这个问题中解释的技术的经典案例,用于regex-match a pattern, exclude..."一个>
This problem is a classic case of the technique explained in this question to "regex-match a pattern, excluding..."
交替的左侧|
匹配完整的然后故意失败,之后引擎跳到下一个字符串中的位置.右侧匹配 url,我们知道它们是正确的,因为它们与左侧的表达式不匹配.
The left side of the alternation |
matches complete <a ...tags </a>
then deliberately fails, after which the engine skips to the next position in the string. The right side matches the urls, and we know they are the right ones because they were not matched by the expression on the left.
我放在右边的 url regex 可以细化,使用任何适合您的需求即可.
The url regex I put on the right and can be refined, just use whatever suits your needs.
参考
这篇关于没有 <a> 的正则表达式匹配链接标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!