Home > Net >  Replace each occurrence of a character but not when it is in a specific word
Replace each occurrence of a character but not when it is in a specific word

Time:02-10

I want to replace occurrences of a character but not when it is part of a specific word in a string using C#.

For example, I want to replace & by an & string but not when the ocurrence is & Another example, a&b&&c would become a&b&&c after the replacement.

I have tried this & (?![&]) but it is not matching multiple occurrences.

Test string: a&&b&&&&&c

CodePudding user response:

In your regex:

& (?![&])

  1. & will match multiple & as a single content. Meaning, if your input has something like: asd&&temp instead of getting asd&&temp you will get asd&temp.

  2. [&] will match only one of the character inside the [] instead of the whole &. So you need to remove the [].

Your changed regex would look like:

&(?!amp;)


&     matches one '&' 
(?!   negative lookahead
amp;  matches 'amp;'
)

Test it here: https://regex101.com/r/d9SlFV/1

CodePudding user response:

Try this one

        string yourString = "a&&b&&&&&c";
        string yourOut = Regex.Replace(yourString, @"&", "dummy");
        sb_trim = Regex.Replace(sb_trim, @"&", "&");
        sb_trim = Regex.Replace(sb_trim, @"dummy", "&");
  • Related