【问题标题】:Regex : replace a phrase only if NOT preceded by a word正则表达式:仅在不以单词开头时才替换短语
【发布时间】:2020-05-21 11:23:54
【问题描述】:
我正在尝试用 perl 命令行替换文本文件中的某些短语(“我的术语”)。这些文件按部分划分,如下所示:
section1
my term
nothing abc
section2
some text
my term
another text
section3
some text
my term
section4
some text
my term
某些部分可能不存在。我想要实现的是用“其他术语”替换“我的术语”,但前提是它在第 1 节中。我尝试了一些前瞻和后视语法,但找不到可行的解决方案 (https://regex101.com/r/mfqay6/1)
例如,如果我删除第 1 节,则以下代码匹配,而我不想要它:
(?!section2).*(my term)
有什么帮助吗?
【问题讨论】:
标签:
regex
perl
regex-lookarounds
【解决方案1】:
一个简单的班轮:
perl -ane 's/my term/some other term/ if(/section1/ ... /section/);print' file.txt
输出:
section1
some other term
nothing abc
section2
some text
my term
another text
section3
some text
my term
section4
some text
my term
【解决方案2】:
这是正则表达式:
((?:section1)(?:(?!my term)(?!^\s*$)[\d\D])+)(my term)
( //start group 1
(?: //start non-capturing group (keeps it organized)
section1 //match section1
) //end non-capturing group
(?: //start another non-capturing group
(?! //start negative lookahead
my term //don't match "my term"
) //end negative lookahead
(?! //start negative lookahead
^\s*$ //don't match an empty line
) //end negative lookahead
[\d\D] //match any character
)+ //repeat this non-capturing group 1 or more times
) //end group 1
(my term) //match "my term" in group 2
下面是替换的内容:
$1my other term
$1 //everything up to "my term", including newline characters
my other term //the other term