替换正则表达式匹配中的字符

Replace characters inside a RegEx match

我想匹配任何文本中的某些行,并且在该匹配项中,我想尽可能频繁地替换某个字符。 示例文本:

Any text and "much" "more" of it. Don't replace quotes here
CatchThis( no quotes here, "any more text" , "and so on and so forth...")
catchthat("some other text" , "or less")
some text in "between"
CatchAnything ( "even more" , "and more", no quotes there, "wall of text")
more ("text"""") and quotes after...

现在我想用井号替换圆括号内的每个引号。 期望的结果:

Any text and "much" "more" of it. Don't replace quotes here
CatchThis( no quotes here, #any more text# , #and so on and so forth...#)
catchthat(#some other text# , #or less#)
some text in "between"
CatchAnything ( #even more# , #and more#, no quotes there, #wall of text# )
more ("text"""") and quotes after...

匹配线条很容易。这是我的模式:

(?i)Catch(?:This|That|Anything)[ \t]*\(.+\)

不幸的是,我不知道如何匹配每个引号并替换它...

你真的需要在正则表达式中替换它吗?如果您的正则表达式找到您想要的内容,您可以替换找到的字符串

上的字符

在 2 个 不同的定界符 中匹配所有出现的某个模式的常用方法是使用基于 \G anchor 的正则表达式。

(?i)(?:\G(?!\A)|Catch(?:This|That|Anything)\s*\()[^()"]*\K"

参见regex demo

解释:

  • (?i) - 不区分大小写的修饰符
  • (?: - 匹配 2 个替代项的非捕获组
    • \G(?!\A) - 字符串中上一次成功匹配之后的位置(因为 \G 也匹配字符串的开头,(?!\A) 是排除这种可能性所必需的)
    • | - 或
    • Catch(?:This|That|Anything) - Catch 后跟 ThisThatAnything
    • \s* - 0+ 个空格
    • \( - 文字 ( 符号
  • ) - 非捕获组结束
  • [^()"]* - 除了 ()"
  • 之外的任何 0+ 个字符
  • \K - 匹配重置运算符
  • " - 双引号。