作为替换的一部分,可以在捕获组上执行其他正则表达式吗?

时间:2014-07-18 13:32:38

标签: regex

因此,可以在捕获组上使用像\ L这样的修饰符使其全部小写,例如\L\2。如果我想作为替换的一部分对捕获组执行额外替换,例如,替换一封信。所以,给定:

cat sat on the mat

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

替代想法:\1{replace c with b}\2

期望的结果:

bat sat on the mat

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

2 个答案:

答案 0 :(得分:1)

对于Javascript:

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

答案 1 :(得分:0)

这是你可以用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