Search code examples
c#regexp-replace

Replace a specific characters after the occurrence of a string using regex.replace


I need to replace after 0x all S to 5. The S are not always at same position, but they are always after 0x.

Example string:
Sunny day Since yesterday 0xS4321S3S

Should be Sunny day Since yesterday 0x54321535

I have tried regex.replace pattern (?<=0x)S, but this just matches the 0x5.


Solution

  • The .NET regex engine supports a lookbehind assertion with an infinite quantifier. If you don't want to cross matching spaces, you can use \S* to match optional non whitespace characters.

    (?<=0x\S*)S
    

    Regex demo