1

How to replace a letter 'b' to 'c' after a duplicate letter 'a' base on 2 times? for example :

ab => ab
aab => aac
aaab => aaab
aaaab => aaaac
aaaabaaabaab => aaacaabaac
2
  • The last example doesn't match in the number of characters (?) Commented May 13, 2017 at 14:51
  • 1
    @SebastiánPalma: I think it's a typo on OP's behalf. Commented May 13, 2017 at 15:05

1 Answer 1

3

You should check groups of aa followed by b and then replace captured groups accordingly.

Regex: (?<!a)((?:a{2})+)b

Explanation:

(?<!a) checks for presence of an odd numbered a. If present whole match fails.

((?:a{2})+)b captures an even number of a followed by b. Outer group is captured and numbered as \1.

Replacement: \1c i.e first captured group followed by c.

Test String:

ab
aab
aaab
aaaab
aaaabaaabaab

After replacement:

ab
aac
aaab
aaaac
aaaacaaabaac

Regex101 Demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.