选择性地用正则表达式替换单词

时间:2015-05-06 11:36:31

标签: regex sublimetext3 pcre

正则表达式是否有可能选择性地替换某些单词?

我的文档包含以下几行:

<type>xxx</type>

其中xxx可以是bugimprovementnewfeature和其他几个值。

我想将其转换为:

"kind":"yyy",

yyy = xxx除了 improvement应该替换为enhancementnewfeature替换为proposal }}。在所有其他情况下,yyy应与xxx相同。

直接正则表达式会将<type>([^<]+)</type>替换为"kind":"$1",,但是可以同时替换这两个特殊字吗?

我相信我正在使用PCRE引擎。

1 个答案:

答案 0 :(得分:2)

不可能将条件语句放在替换字符串中,也不可能在模式本身中存储数据(不在字符串中)。

使用sublimetext更简单的方法显然是在几个步骤中进行(之前替换特殊字符串,然后替换一般情况)。好方法是使用编程语言和xml解析器。

但是可以用一招来一次性替换所有:

1)在文件的最末端添加此行(在新行中):

#improvement:enhancement#newfeature:proposal#"kind":"

2)使用这种模式:

<type>(?|([^<]+)</type>(?=(?:.*\R)++#(?>[^:]+:[^#]+#)??\1:([^#]++).*#((.).*))|(([^<]+))</type>(?=(?:.*\R)++.*#((.).*)))|\R.*\z

有了这个替代品:

$3$2$4

$3代表"kind":"或没有,$2代表enhancementproposalxxx或任何内容,{ {1}}代表$4或什么都没有。)

3)replaceAll

demo

这个想法很简单:将所有替换内容放在字符串本身中,并在模式中使用分支重置"(每个替代中的此功能捕获组具有相同的数字)。添加的行会自动删除。

注意:如果您要更换两个以上的特殊字词,请填写最后一行(但(?|.(..).|.(..).)必须留在最后),然后更改"kind":"模式为??

模式细节:

*?

<type> (?| # open a branch reset group # first branch: the special terms ([^<]+) # capture the term in group 1 </type> (?= # open a lookahead (nothing is consumed inside it) (?:.*\R)++ # # reach the last line (?>[^:]+:[^#]+#)?? # skip a couple of term:repl if needed \1 # until the content of group 1 is found : ([^#]++) # capture the corresponding replacement .* # # reach the last # ((.).*) # capture '"kind":"' in group 3 and '"' in group 4 ) # close the lookahead | # OR second branch: the general case (([^<]+)) # capture the term in group 1 and 2 # (to have the same number than the previous branch) </type> (?= # open a lookahead (?:.*\R)++ # same thing than the previous branch .* # # but this time only '"kind":"' and '"' ((.).*) # are needed ) ) # close the branch reset group | # OR \R.*\z # the last line (in this case all the # groups are empty) 是几种类型换行符的别名(无论系统如何)。

\R是一个原子组。

(?>....)++*+是占有量词。

?+是字符串结尾的锚点。

相关问题