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

Viewed 161

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.

2 Answers

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

After a serious struggle, I came up with this idea:

(?:(\G|^)|)(?(1)(?:a+|\d+([^a\d]+))|\d+)

Replace with

x$2
  • (?:(\G|^)|)

Testing last anchor \G or the start of the string ^ before every match optionally, and put the caught anchor in group 1

  • (?(1)(?:a+|\d+([^a\d]+))|\d+)
  • If cause, if the anchor has been detected, matching a+ or \d+
  • If the sequence detected is \d+, also matches the ([^a\d]+) to keep the anchor for next match.
  • If the sequence detected is a+, only matches a+, so the anchor will be broken for the next test.
  • While the anchor \G is not detected in group 1, that means a+ has already been detected, after that only matches \d+, and the \G will never be detected anymore.

Here's the proof

It seems it is only useful in this scenario, not sure if it's useful for the real question, though.

Related