【问题标题】:How to replace the second matched word in every line?如何替换每行中的第二个匹配词?
【发布时间】:2020-05-12 02:21:29
【问题描述】:

我有一个包含大约 10000 行的 txt 文件。在每一行中,我都有一个重复两次的特定字符 (%20)。我需要用另一个词替换第二个出现并保留第一个。是否有任何 Notepad++ 正则表达式?

这是我的文字:

My name is %20John. my friend's name is %20john too.
My name is %20paul. my friend's name is %20paul too.
.
.

我需要它是这样的:

My name is %20John. my friend's name is john too.    
My name is %20paul. my friend's name is paul too.

【问题讨论】:

    标签: regex replace notepad++


    【解决方案1】:

    你可以这样使用:

    ^(.+?%20.+?)%20
    

    ..并替换为:

    \1
    

    ..这将删除第二次出现的%20。如果您想用其他东西替换它(例如,SomeWord),您可以在“替换为”字段中使用\1SomeWord

    Demo.

    【讨论】:

    • 谢谢。它工作得很好,但有一些我忘了提。 (%20)s 的数量在每一行中有所不同,我在某些行中甚至有 10 个,因此这个正则表达式在这些行中不起作用。所有行中都有一些常量部分,它是 (dl=0">)。我需要删除此常量之后的所有 (%20) 并用空格替换它。不应删除此常量之前的所有 (%20) . 你能帮我吗?例如:%20my %name %is %john dl=0"> %20my %name %is %john 应该更改为:%20my %name %is %john dl=0"> 我的名字是约翰
    • @Sanila 这听起来像是一个不同的问题,所以我想说这可能是ask a new one 的好时机。
    【解决方案2】:

    试试这段代码,它会按预期完成工作......

    查找内容:(.*?\K%){2}\d+
    替换为:nothing

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2021-05-19
      相关资源
      最近更新 更多