使用 Notepad++ 删除部分文本仅出现一次

问题描述 投票:0回答:1

我可以使用正则表达式删除文本,但是如果文本的特定部分仅在文件中出现一次,有没有办法有条件地删除文本?

例如,如果我搜索flag_abc=.*,我将得到以下所有结果

flag_abc=10000001
flag_abc=10000002
flag_abc=10000003
flag_abc=10000004
flag_abc=10000005
flag_xyz=10000005
flag_abc=10000006
flag_abc=10000007

10000001、10000003、10000004和10000006只能找到一次,并且只出现在包含flag_abc=的行中 但是,10000002、10000005 和 10000007 可以在超过 1 行中找到。代码行数不一致。 flag_abc= 始终采用相同的格式,并且数字始终为 8 位数字。原始代码如下所示:

<lines of code>
flag_abc=10000001
<lines of code>
flag_abc=10000002
<lines of code>
property_ghi=10000002
<lines of code>
flag_abc=10000003
<lines of code>
flag_abc=10000004
<lines of code>
flag_abc=10000005
<lines of code>
flag_uvwxyz=10000005
<lines of code>
flag_abc=10000006
<lines of code>
flag_abc=10000007
<lines of code>
10000007{}
<lines of code>

我正在尝试删除 flag_abc=xxxxxxxx 的所有实例,其中 xxxxxxxx 仅出现一次,仅出现在“flag_abc=”旁边。如果 xxxxxxxx 出现在“flag_abc=”旁边,但也出现在代码中的其他任何位置,无论代码中的位置如何,则保留该行。所以上面的代码最终应该看起来像:

<lines of code>
<lines of code>
flag_abc=10000002
<lines of code>
property_ghi=10000002
<lines of code>
<lines of code>
<lines of code>
flag_abc=10000005
<lines of code>
flag_uvwxyz=10000005
<lines of code>
<lines of code>
flag_abc=10000007
<lines of code>
10000007{}
<lines of code>

我浏览了 NPP 手册的搜索部分,但找不到任何检查字符串唯一性的表达式。使用搜索表达式这是否可行?

notepad++
1个回答
0
投票
  • Ctrl+H
  • 查找内容:
    ^flag_abc=(\d{8})\b[\s\S]*?\b\1\b(*SKIP)(*FAIL)|^flag_abc=\d{8}\R
  • 替换为:
    LEAVE EMPTY
  • 勾选环绕
  • SELECT 正则表达式
  • 取消勾选
    . matches newline
  • 全部替换

说明:

  ^               # beginning of line
    flag_abc=       # literally
    (\d{8})         # group 1, 8 digits
    \b              # word boundary, not matching 9 digits
    [\s\S]*?        # 0 or more any character, not  greedy
    \b              # word boundary
    \1              # backreference to group 1, same 8 digit number
    \b              # word boundary
    (*SKIP)         # skip this match
    (*FAIL)         # and considere it failled
|               # OR
  ^               # beginning of line
    flag_abc=       # literally
    \d{8}           # 8 digits
    \R              # any kind of linebreak

截图(之前):

截图(之后):

© www.soinside.com 2019 - 2024. All rights reserved.