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?
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 au
. 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 matchcab
, but matches theb
(and only theb
) in bed or debt.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With