仅替换正则表达式匹配的一部分 [英] Replacing only a part of regexp matching

查看:302
本文介绍了仅替换正则表达式匹配的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下javascript代码:

please consider the following javascript code:

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

它给出了 myObjectxxx); as .myMethod(已被选中。

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

现在我只会选择 myMethod 。换句话说,我想选择以开头的任何单词。并以<$结尾c $ c>((不包括)。

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

谢谢,Luca。

推荐答案

一般答案:使用括号捕获要保留的部分,并将其作为 $ 1 包含在替换字符串中。

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

有关详细信息,请参阅任何regexp替换教程。

See any regexp substitution tutorial for details.

此处:只包含和替换字符串中的

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

对于练习,写一个将要转的正则表达式方案的任何字符串 - ABC - DEF - - DEF - ABC - 任意让ter-values ABC DEF 。所以 - XY - IJK - 应该变成 - IJK - XY - 。在这里,您确实需要使用捕获组和反向引用。

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

这篇关于仅替换正则表达式匹配的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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