【问题标题】:replace groups in regex loop替换正则表达式循环中的组
【发布时间】:2020-06-10 10:28:54
【问题描述】:

我有这两行:

What is P(output1|cause1=2, cause2=2)
What is P(output2|cause3=2)

我想改成:

method_to_use(model, {"cause1": 2, "cause2": 2}, "output1")
method_to_use(model, {"cause3": 2}, "output2")

这是我的正则表达式:

.*P[(]([a-z1-9]+)[|](([a-z1-9]+)=([1-9]),?)+[)]

我尝试像这样替换它:

method_to_use(model, {"$3": $4}, "$1")

但我只得到了小组中的最后一个:

method_to_use(model, {"cause2": 2}, "output1")

是否有可能做某种“循环”并在途中改变所有配合?

【问题讨论】:

  • 什么是编程语言/工具?
  • 这个工具很棒
  • 1) 将.*P\( 替换为method_to_use(,2) \(\K(\w+)\|([^()]+) 替换为model, {$2}, "$1",3) (\w+)=(\w+) 替换为"$1": $2。有一件事是肯定的:你不能用一个正则表达式来做到这一点。

标签: regex sublimetext3 regex-group


【解决方案1】:

你可以用下面的正则表达式匹配字符串。

^.*P\(([^|]+)\|([^=]+)=(\d+)(?:, +([^=]+)=(\d+))?\)$

如果捕获组 4 非空,则将(整个字符串)匹配替换为

method_to_use(model, {"$2": $3, "$4": $5}, "$1")

这会导致字符串

What is P(output1|cause1=2, cause2=2)

替换为

method_to_use(model, {"cause1": 2, "cause2": 2}, "output1") 

Demo 1

如果捕获组 4 为空,则将匹配替换为

method_to_use(model, {"$2": $3}, "$1")

这会导致字符串

What is P(output2|cause3=2)

替换为

method_to_use(model, {"cause3": 2}, "output2")

Demo 2

请注意,两个链接的正则表达式是等价的,唯一的区别是在演示 1 中,我以 free-spacing 模式表达了正则表达式,这允许它是自记录的。

当然可以简单地从捕获组的值中形成新字符串,而不是替换整个字符串。如果这样做了 ^.*P 在正则表达式的开头可以简单地更改为 P

正则表达式引擎执行以下操作。

^             # match beginning of line
.*P\(         # match 0+ chars then '|('      
([^|]+)       # save 1+ chars except '|' in cap grp 1 (output)    
\|            # match ':'
([^=]+)       # save 1+ chars except '=' in cap grp 2 (causeA)
=             # match '='
(\d+)         # save 1+ digits in cap grp 3 (causeAval)
(?:           # begin non-cap grp
  ,\ +        # match ',' then 1+ spaces
  ([^=]+)     # match 1+ chars except '=' in cap grp 4 (causeB)   
  =           # match '='
  (\d+)       # match 1+ digits in cap grp 5 (causeBval)
)?            # end non-cap grp and make it optional  
\)            # match ')'
$             # match end of line

【讨论】:

    【解决方案2】:

    有一件事是肯定的:你不能用一个正则表达式来做到这一点。

    您可以使用三步法:

    • .*P\( 替换为method_to_use(
    • \(\K(\w+)\|([^()]+) 替换为model, {$2}, "$1"
    • (\w+)=(\w+) 替换为"$1": $2

    注意

    • .*P\( 尽可能多地匹配除换行符之外的任何 0 个或多个字符,P(
    • \(\K(\w+)\|([^()]+) 匹配(,然后将其从匹配值中与\K 丢弃,然后将1+ 个单词字符捕获到第1 组(替换模式中的$1),匹配| 然后1+ )( 以外的字符被捕获到第 2 组 ($2)
    • (\w+)=(\w+) - 1+ 个单词字符被捕获到第 1 组($1 在替换模式中),= 被匹配,然后 1+ 个单词字符被捕获到第 2 组($2)。

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-25
      • 2012-08-01
      相关资源
      最近更新 更多