且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-23 13:51:59

一般答案:使用括号捕获要保留的部分,并将其作为 $ 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.