javascript 使用正则表达式仅用 JS 替换最后一次出现的模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4744689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:45:36  来源:igfitidea点击:

Using regex to replace only the last occurrence of a pattern with JS

javascriptregex

提问by AriehGlazer

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:

我有一个案例,我试图用另一种模式替换某个模式。我的问题是我只需要替换该模式的最后一次出现,而不是全部。我发现了这个问题:

How to replace last occurrence of characters in a string using javascript

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

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:

但它不符合我的需求。作为背景,我会说我正在尝试替换 CSS 规则,但对于当前示例,让我们看看这段文字:

abcd:bka:

bbb:aad:

accx:aaa:

bbb:a0d:

cczc:aaa:

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

假设我只想替换 bbb 的值。我目前的规则是

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

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.

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

回答by Tim Pietzcker

Try

尝试

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

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

否定前瞻断言确保bbb:文本中没有进一步的内容。周围的括号[^:]+是不必要的。

Explanation:

解释:

(?!       # 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

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

[\s\S],因为JavaScript没有一个选项,以使点以匹配新行的解决办法是必要的。