这可能通过正则表达式条件吗?

Is this possible via regex conditional?

假设我已经成功捕获了以下组:

/1 "text1"
/2 "notation1"

现在,我想用 "newtext1" 替换 /1,前提是 /2 包含 "notation1"。这可以通过条件语句实现吗?

或者通过任何其他方法?

假设您在 perl 中,替换将由 e(将字符串作为运算符计算)修饰符和三元条件运算符完成。

$s = "text1 notation1";
$s=~s/(\w+)\s(\w+)/( eq "notation1")?"newtext1 ":"  "/e;
print $s;

Regex 没有条件语句可以让您检查捕获组是否捕获了某个值。您有两个选择:

  1. 更改模式,使其仅在找到 notation1 时匹配,即 regex=(text1)(notation1),replacement=newtext1.
  2. 如果您的编程语言支持,请创建一个替换函数来检查第 2 组的内容和 returns 所需的替换字符串。例如在 python 你可以这样做: re.sub(r'(text1)(notation1)', lambda match: 'newtext1notation1' if match.group(2)=='notation1' else 'text1notation1', 'text1notation1')