Search code examples
regexpcresubstitution

Regex Substitution: only replace the first occurance from a "or" condition


I need to replace \d+ and a+ to x, I want to replace all the \d+ to x, but for a+, I only want to replace the first occurance if there's any.

Is it possible to use only one regex to achieve this?

Input Desired Output
123,456,789 x,x,x
123,456,a,789 x,x,x,x
aaa,aa,aaa x,aa,aaa
aa,123,456,aaaa,789 x,x,x,aaaa,x
aaa,123,456,aa,789,aaaa x,x,x,aa,x,aaaa

This sure does not work:

/\d+|a+/gm

I'm using PCRE regex engine, or is there any mode modifier or control verb can do this? Thanks in advance.


Solution

  • Sorry I forget that answer must be posted aside and post it in comments at first.

    Now here it is:

    Regex: \d+|((?<!a|(?!(?1)).))a+

    Replacement: x

    https://regex101.com/r/v24o7B/1