如何用regexp一次搜索并替换3个作业



我正在使用一个名为ASR(实际搜索和替换)的程序,该程序内置了一些强大的功能,可以使用regexp搜索文本并替换它。

我经常使用它,我把它写进了我的工作流程中。

问题是,我需要替换三个搜索来更正配置文件(仅从这三行中去掉"-"),这都是手动工作,非常耗时。

配置文件在文件中随机获得了以下行,这些行可能会以不同的名称和编号出现多次。它们总是在一条线上。

<id>filename-33</id>
<source>#filename-33</source>
<url>{filename-33}</url>

所需输出应为:

<id>filename33</id>
<source>#filename33</source>
<url>{filename33}</url>

"filename"和数字"33"都可以是任何东西(filename始终是一个小写名称,没有特殊字符,数字始终是0到1000之间的数字)。

我知道如何找到并替换所有三行:

<source>#(.*)-     replace with      <source>#$1
<url>{(.*)-        replace with      <url>{$1
<id>(.*)-          replace with      <id>$1

但这必须分三次进行。

我的问题是,是否可以只使用一个查找行和一个替换行进行搜索和替换?

问候,

Arjan

您可以使用交替(使用|管道操作符)来创建一个匹配所有3种模式的表达式,并创建一个替换。

替换此模式:

(?:<source>(?=#)|<url>(?={)|<id>)([^-]+)-

与CCD_ 2的组合应该产生正确的输出。

https://regex101.com/r/mS3mP9/3

表达式分析:

(             // begin capturing group
<source># // find the opening <source> tag followed by a #
| <url>{    //  ...or find the opening <url> tag followed by a {
| <id>      // ...or find the opening <id> tag
)             // end capturing group
([^-]+)       // capture everything that is not a hyphen
-             // match and consume the hyphen

可以使用^(<(?:id|source|url)>(#|{)?w+)-并用$1替换它,如下所示。