红宝石正则表达式使子停止在第一场比赛

发布于 2024-12-05 19:32:06 字数 334 浏览 4 评论 0原文

我正在尝试替换文本字符串中的特定模式。 该模式是包含单词“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素染倾城色 2024-12-12 19:32:06

您的表达式是贪婪的,因为只要模式仍然匹配, .+? 实际上就会继续匹配任何字符。

只需使用您已在正则表达式末尾使用的 [^>]* 字符集即可:

ccontent.sub(/<a [^>]*href=\"([^\"]+)\"[^>]*>Sak<\/a>/,  '')

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:

ccontent.sub(/<a [^>]*href=\"([^\"]+)\"[^>]*>Sak<\/a>/,  '')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文