红宝石正则表达式使子停止在第一场比赛
我正在尝试替换文本字符串中的特定模式。 该模式是包含单词“sak”的 href。
我的脚本目前如下所示:
ccontent=ccontent.sub(/<a .+?href=\"([^\"]+)\"[^\>]*>Sak<\/a>/, '')
问题是这替换了整个字符串。 (该字符串包含两个链接)。 问题出在“a .+?”符号周围,它贯穿我想要完全替换的链接,并进入下一个链接并替换整个链接。
但我希望它在第一个模式匹配时停止达到,以便它只删除“sak”链接,
如何使模式匹配在第一次到达“href”时停止?
I am trying to replace a specific pattern in a text string.
That pattern is a href containing the word "sak".
My script currently looks like this:
ccontent=ccontent.sub(/<a .+?href=\"([^\"]+)\"[^\>]*>Sak<\/a>/, '')
The problem is that this replaces the entire string. (the string contains two links).
The problem is somewhere around the `a .+?" symbols, it runs through the link i want to Replace entirely and goes into the next link and replaces that whole link as well.
But I want it to STOP when the first pattern match is reached so that it only erases "sak" link.
How do i make the pattern match stop at the first time it reaches the 'href'?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的表达式是贪婪的,因为只要模式仍然匹配,
.+?
实际上就会继续匹配任何字符。只需使用您已在正则表达式末尾使用的
[^>]*
字符集即可:Your expression is greedy, because
.+?
will actually keep matching any character as long as the pattern still matches.Just use the
[^>]*
character set you're already using at the end of the regex: