【问题标题】:How do I replace 'string1' with 'string2' if line contains 'string3' in Notepad++?如果 Notepad++ 中的行包含“string3”,如何将“string1”替换为“string2”?
【发布时间】:2017-10-17 20:09:43
【问题描述】:

我在文件中有以下内容:

This is line one
This is line two with string1 and string3
This is line three with string3

如果该行包含“string3”,我需要将“string1”替换为“string2”,这样结果将是:

This is line one
This is line two with string2 and string3
This is line three with string3

【问题讨论】:

  • @wiktor stribizew,这不是“正则表达式:删除包含的行”的重复项。我不想删除行。
  • @WiktorStribiżew 方法可能是,但如果有人试图找到解决我面临的问题的方法,他们将不会搜索“删除包含的行”。
  • 好的,那你的问题是什么?你被困在哪里了?此外,您还没有解释string3 可能出现的位置。从您的示例来看,string3 似乎应该遵循`string2,是这样吗?
  • @WiktorStribiżew:我同意海星的观点,这不是现有问题的完全重复...
  • @Starfish:试试这个,它在记事本++上对我有用:regex101.com/r/4L5Wyx/1

标签: regex replace notepad++


【解决方案1】:

要在包含string3 anywhere 的任何行上替换string1所有出现,您需要使用基于\G 的正则表达式:

(?:\G(?!^)|^(?=.*string3)).*?\Kstring1

替换为string2。请参阅regex demo online

详情

  • (?:\G(?!^)|^(?=.*string3)) - 上一场比赛的结尾或包含 string3 的行的开头
  • .*? - 除换行符以外的任何 0+ 个字符
  • \K - 匹配重置运算符丢弃当前迭代中到目前为止匹配的所有文本
  • string1 - 要替换​​的 string1 子字符串。

以下文字

This is line string1
This is line two with string1 and string3 string1
This is line two with string1 string1 and string3 
This is line three with string3
This is line string3 with string1 and string1

变成

【讨论】:

  • 感谢您的回答
【解决方案2】:

代表@Gawil

在 Notepad++ 上转到搜索->替换

在“查找内容”下:^(?=.*?string3)(.*?)string1(.*?)$

在“替换为”下:\1string2\2

根据需要执行“替换”或“全部替换”。

【讨论】:

  • 这样,您只需替换 一次出现string1。请参阅我的答案,其中显示了如何替换包含 string3 的行上所有出现的单词。
  • @WiktorStribiżew 是的,我不得不多次点击“全部替换”
  • @Starfish:对不起,我没有预料到string1会在一行中出现多次
猜你喜欢
  • 1970-01-01
  • 2021-07-10
  • 2014-09-09
  • 2015-07-23
  • 2020-10-08
  • 2018-02-25
  • 2023-03-28
  • 1970-01-01
  • 2020-01-15
相关资源
最近更新 更多