Jim
Jim

Reputation: 701

Possible to perform additional regex on a capturing group as part of replacement?

So it's possible to use modifiers like \L on a capturing group to make it all lower case, e.g. \L\2. What if I want to perform an additional replacement on a capturing group as part of the replacement, e.g. replace a letter. So, given:

cat sat on the mat

regex: (\w)(at)

replacement idea: \1{replace c with b}\2

desired result:

bat sat on the mat

Edit: I would prefer the solution to not need to access the matching groups as a second step (that's a somewhat obvious solution and doesn't match my criteria above of the "replacement idea" having some kind of indicator in the actual replacement string itself that indicates that a further replacement must occur). If this is not possible in any flavour of regex, I would like to know this. The language used to solve this does not matter to me, I'm not constricted by language.

Upvotes: 0

Views: 63

Answers (2)

Unihedron
Unihedron

Reputation: 11041

For Javascript:

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

Upvotes: 1

TheLostMind
TheLostMind

Reputation: 36304

This is how you can do it in Java.

If you want all c's in all groups to be replaced by b, you could use

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 

Upvotes: 0

Related Questions