Notepad++ 中的正则表达式 "Replace Text + Value" ==> "New Text + Value"

Regex in Notepad++ "Replace Text + Value" ==> "New Text + Value"

我重写了一些东西,现在我需要替换很多文件,它们包含以下内容:

TOOL_ID = 1

TOOL_NAME = "Calc"

需要替换为:

Application_ID = (1)

Application_Name = "Calc"

到目前为止,我的尝试如下:

(?<=TOOL_ID = ) 这 returns 至少 1. 但我不确定如何将其输出为正确的输出。因为如果我这样做:

Application_ID($&) 它只是将它替换为: TOOL_ID = Application_ID1 (它甚至不使用“()”)

希望有人得到一些甜蜜的提示:)

如果您有这 2 个值,则可以使用 2 个捕获组并使用条件替换。

\bTOOL_(ID|NAME)\h+=\h+(?:(\d+)|("Calc"))

或者匹配单词字符而不是 CalcIDNAME

\bTOOL_([A-Z]+)\h+=\h+(?:(\d+)|("\w+"))

说明

  • \bTOOL_([A-Z]+) 匹配 Tool_ 并在 组 1 中捕获 1+ 个大写字符 A-Z 在组 1
  • \h+=\h+ 在 1+ 个水平空白字符之间匹配 =
  • (?:非捕获组
    • (\d+) 捕获 组 2,匹配 1+ 个数字
    • |
    • ("\w+") 捕获 组 3,匹配双引号之间的 1+ 个单词字符
  • ) 关闭群组

Regex demo

在第2组的替换测试中。如果存在,则替换为第1组和第2组,否则替换为第1组和第3组。

Application_(?{2} = \(\): = )

这对我有用,除了数字 1 周围的结束括号:

  • Ctrl+H
  • 查找内容:(?:(TOOL_ID) = (\d+)|(TOOL_NAME) =)
  • 替换为:(?1Application_id = \(\))(?3Application_Name = )
  • 检查 匹配大小写
  • 检查 环绕
  • 检查 正则表达式
  • 取消选中 . matches newline
  • 全部替换

解释:

(?:                     # non capture group
    (TOOL_ID)           # group 1, literally
    =                   # equal sign
    (\d+)               # group 2, value
  |                   # OR
    (TOOL_NAME) =       # group 3, literally
)

替换:

(?1                         # if group 1 exists (TOOL_ID)
    Application_id =          # replace with Application_id
    \(\)                    # the value suround with parentheses that have to be escaped in Notepad++
)                           # end if
(?3                         # if group 3 exists (TOOL_NAME)
    Application_Name =        # replace with Application_Name
)                           # endif

截图(之前):

截图(后):