Regex 正则表达式:仅当前面没有单词时才替换短语
我试图用perl命令行替换文本文件中的一些短语(“我的术语”)。这些文件按节进行划分,如下所示:Regex 正则表达式:仅当前面没有单词时才替换短语,regex,perl,regex-lookarounds,Regex,Perl,Regex Lookarounds,我试图用perl命令行替换文本文件中的一些短语(“我的术语”)。这些文件按节进行划分,如下所示: section1 my term nothing abc section2 some text my term another text section3 some text my term section4 some text my term 有些部分可能不存在。我想要实现的是用“其他术语”替换“我的术语”,但前提是它在第1节中。我尝试了一些lookahead和lookbehinds语法,
section1
my term
nothing abc
section2
some text
my term
another text
section3
some text
my term
section4
some text
my term
有些部分可能不存在。我想要实现的是用“其他术语”替换“我的术语”,但前提是它在第1节中。我尝试了一些lookahead和lookbehinds语法,但找不到有效的解决方案()
例如,如果我删除了第1节,则以下代码匹配,而我不需要它:
(?!section2).*(my term)
有什么帮助吗?简单的一行:
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
以下是正则表达式:
((?: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
这就是你想要的吗:是的,这就是我想要的。有点迷路了,谢谢。谢谢你的解释,尽管我需要一行perl命令。