Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one character but not two in a string

Tags:

c#

regex

I want to replace single occurrences of a character but not two in a string using C#.

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

If I use a regex like &[^&], it will also match the character after the & and I don't want to replace it.

Another solution I found is to iterate over the string characters.

Do you know a cleaner solution to do that?

like image 675
dhalfageme Avatar asked Sep 16 '25 12:09

dhalfageme


2 Answers

To only match one & (not preceded or followed by &), use look-arounds (?<!&) and (?!&):

(?<!&)&(?!&)

See regex demo

You tried to use a negated character class that still matches a character, and you need to use a look-ahead/look-behind to just check for some character absence/presence, without consuming it.

See regular-expressions.info:

Negative lookahead is indispensable if you want to match something not followed by something else. When explaining character classes, this tutorial explained why you cannot use a negated character class to match a q not followed by a u. Negative lookahead provides the solution: q(?!u).

Lookbehind has the same effect, but works backwards. It tells the regex engine to temporarily step backwards in the string, to check if the text inside the lookbehind can be matched there. (?<!a)b matches a "b" that is not preceded by an "a", using negative lookbehind. It doesn't match cab, but matches the b (and only the b) in bed or debt.

like image 113
Wiktor Stribiżew Avatar answered Sep 19 '25 03:09

Wiktor Stribiżew


You can match both & and && (or any number of repetition) and only replace the single one with an empty string:

str = Regex.Replace(str, "&+", m => m.Value.Length == 1 ? "" : m.Value);
like image 30
Guffa Avatar answered Sep 19 '25 05:09

Guffa