Home > Software design >  Globally replace all hyphens after some 'Divider'
Globally replace all hyphens after some 'Divider'

Time:09-16

Greetings to the experts, Im seeking a PCRE match/replace to perform the following...
a-b-Divider-Any-Text ----> a-b-Divider__Any__Text
a-b-c-Divider-w-x-y-z ---> a-b-c-Divider__w__x__y__z
a-b-c-d-e-f-g-h-i-j ------> a-b-c-d-e-f-g-h-i-j     (nothing replaced, since no Divider)

So basically, I'm just trying to globally replace all of the hyphens after Divider.
If replacing hyphens before a Divider, I just use something like -(?=.*Divider.*)/g
But changing this to a negative-lookahead also matches text without the Divider.

Can I somehow both verify 'Divider' while globally matching all of the remaining hyphens??

CodePudding user response:

You can use

(?:\G(?!\A)|Divider)[^-]*\K-

See the regex demo. Details:

  • (?:\G(?!\A)|Divider) - either the end of preceding match or Divider
  • [^-]* - zero or more chars other than -
  • \K - match reset operator that discards text matched so far
  • - - a hyphen.
  • Related