使用正则表达式仅用JS替换模式的最后一次出现 [英] Using regex to replace only the last occurrence of a pattern with JS

查看:113
本文介绍了使用正则表达式仅用JS替换模式的最后一次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,我试图用另一种模式替换某种模式.我的问题是,我只需要替换该模式的最后一次出现,而不是全部替换即可.我发现了这个问题:

I have a case where I'm trying to replace a certain pattern with another. My problem is that I need to only replace the last occurrence of that pattern, not all of them. I've found this question:

如何替换最后一次出现使用javascript的字符串中的字符

但这不符合我的需求.作为背景,我会说我正在尝试替换CSS规则,但是对于当前示例,请看下面的文本:

But it doesn't fit my needs. As a background, I will say that I am trying to replace a CSS rule, but for the current example lets look at this text:

abcd:bka:

bbb:aad:

accx:aaa:

bbb:a0d:

cczc:aaa:

让我说我只想替换bbb的值.我当前的规则是

lets say I only want to replace the value of bbb. My current rule will be

text.replace(/(\s*bbb:)([^:]+)/,"$1aaa")

,但它只会替换第一个匹配项,而我希望它替换最后一个匹配项.我当前的模式实际上比这更复杂,但是我认为伪问题就足够了.

but it will only replace the first match, while I want it to replace the last one. My current pattern is actually more complex than this one, but I think the pseudo problem will suffice.

推荐答案

尝试

text.replace(/(\s*bbb:)(?![\s\S]*bbb:)[^:]+/,"$1aaa")

否定的超前断言可确保文本前面没有进一步的 bbb:. [^:] + 周围的括号是不必要的.

The negative lookahead assertion makes sure that there is no further bbb: ahead in the text. The parentheses around [^:]+ are unnecessary.

说明:

(?!       # Assert that it is impossible to match the following after the current position:
 [\s\S]*  # any number of characters including newlines
 bbb:     # the literal text bbb:
)         # End of lookahead assertion

[\ s \ S] 解决方法是必需的,因为JavaScript没有允许点与换行符匹配的选项.

The [\s\S] workaround is necessary because JavaScript doesn't have an option to allow the dot to match newlines.

这篇关于使用正则表达式仅用JS替换模式的最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆