javascript 仅替换正则表达式匹配的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8995322/
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-26 05:16:00  来源:igfitidea点击:

Replacing only a part of regexp matching

javascriptregex

提问by lviggiani

please consider the following javascript code:

请考虑以下 javascript 代码:

"myObject.myMethod();".replace(/\.\w+\(/g, "xxx");

it gives "myObjectxxx);" as ".myMethod(" is selected.

它给出“ myObjectxxx);”,因为“ .myMethod(”被选中。

Now I would only select myMethodinstead. In other words I want to select any word starting with .and ending with ((excluded).

现在我只会选择myMethod。换句话说,我想选择.((排除)开头和结尾的任何单词。

Thanks, Luca.

谢谢,卢卡。

回答by Has QUIT--Anony-Mousse

General answer: Capture the part that you want to keep with parentheses, and include it in the substitution string as $1.

一般答案:用括号捕获要保留的部分,并将其作为$1.

See any regexp substitution tutorial for details.

有关详细信息,请参阅任何正则表达式替换教程。

Here: just include the .and the (in your substitution string.

此处:只需在替换字符串中包含.(

For an exercise, write a regexp that will turn any string of the scheme --ABC--DEF--to --DEF--ABC--for arbitrary letter-values of ABCand DEF. So --XY--IJK--should turn into --IJK--XY--. Here you really need to use capture groups and back references.

为了练习,写一个正则表达式将会把该计划的任何字符串--ABC--DEF----DEF--ABC--为任意字母值ABCDEF。所以--XY--IJK--应该变成--IJK--XY--. 在这里,您确实需要使用捕获组和反向引用。

回答by Joey

You can use lookaroundassertions:

您可以使用环视断言:

.replace(/(?<=\.)\w+(?=\()/g, 'xxx')

Those will allow the match to succeed while at the same time not being part of the match itself. Thus you're replacing only the part in between.

这些将使比赛成功,同时又不成为比赛本身的一部分。因此,您只替换了两者之间的部分。

The easier option for people unfamiliar with regexes is probably to just include the .and (in the replacement as well:

对于不熟悉正则表达式的人来说,更简单的选择可能是将.和也包含(在替换中:

.replace(/\.\w+\(/g, ".xxx(")

回答by Eric Wendelin

I'd suggest a slightly different approach:

我建议采用稍微不同的方法:

"myObject.myMethod();".replace(/^([^\.]*\.)\w+(\(.*)$/g, "xxx");

though simpler solutions have been suggested.

尽管已经提出了更简单的解决方案。