【问题标题】:Possible to perform additional regex on a capturing group as part of replacement?作为替换的一部分,可以在捕获组上执行额外的正则表达式吗?
【发布时间】:2014-09-09 16:00:41
【问题描述】:

因此可以在捕获组上使用诸如 \L 之类的修饰符以使其全部小写,例如\L\2。如果我想在捕获组上执行额外的替换作为替换的一部分,例如替换一个字母。所以,给定:

cat sat on the mat

正则表达式:(\w)(at)

更换思路:\1{replace c with b}\2

想要的结果:

bat sat on the mat

编辑:我希望解决方案不需要访问匹配组作为第二步(这是一个有点明显的解决方案,不符合我上面的“替换想法”标准实际替换字符串本身中的某种指示符,表明必须进行进一步替换)。 如果这在任何正则表达式中都不可能,我想知道这一点。用来解决这个问题的语言对我来说并不重要,我不受语言的限制。

【问题讨论】:

  • 首先,您使用的是什么语言?
  • 我正在寻找一种与语言无关的方式来实现这一点,这种方式在 Notepad++ 或 Python 中同样适用。典型的正则表达式引擎中不存在此功能吗?
  • 正则表达式引擎因语言实现而异。
  • 没有什么叫language agnostic regex
  • 你不会单独使用正则表达式来做到这一点......

标签: regex


【解决方案1】:

对于 Javascript:

var replaced = "cat sat on the mat".replace(/(\w)(at)/g, function($0, $1, $2){return $1.replace(/c/g, "b") + $2;})

【讨论】:

  • 在 OP 指定他的编程语言之前,这是一个简单的解决方案。例如,我知道在 Java 中会使用.group()
  • +1 用于替换 lambda(C# 中的委托,PHP 中的 preg_replace 等)
【解决方案2】:

这就是您在 Java 中可以做到的方式。

如果您希望所有组中的所有c 都替换为b,您可以使用

public static void main(String[] args) {
    String s = "cat sat on the mat with another cat which was fat";
    Pattern p = Pattern.compile("(\\w+)");
    Matcher m = p.matcher(s);

    while (m.find()) {
        System.out.print(m.group(1).replace('c', 'b') + " ");
    }

}

input : "cat sat on the mat with another cat which was fat";
output : bat sat on the mat with another bat whibh was fat 

【讨论】:

  • OP 希望为捕获的组 1“用 b 替换 c”,而不是将等于它的第一个字符的任何内容替换为“b”。另外,如果你这样做,如果没有匹配,你会得到一个例外。
  • @Unihedron - 将任意组中的 any c 替换为 b ?
  • @Unihedron - 编辑了我的答案..我对 OP 问题的理解仍然错误吗?
  • 看起来不错。 cat sat on the mat with another cat which was fat 将变为 bat sat on the mat with another bat which was fat,因为 OP 的初衷是替换 (\w)(at) 的第一组中的字符,虽然刚才我意识到你可以替换整个匹配,因为第 2 组中不能有 'c'无论如何。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
相关资源
最近更新 更多