Zamir
Zamir

Reputation: 81

C# RegEx Selective Replacement

I am trying to do a selective replacement, so replace everything in a string but not the characters between [ & ].
For example if the input string is “yyyy[m]mm”, I want to replace all m to upper case (except the ones between [ & ]), the result should be yyyy[m]MM.

Any ideas?

Thanks.

Upvotes: 0

Views: 167

Answers (1)

Tim S.
Tim S.

Reputation: 56556

This will do it, at least in your example. It uses a negative lookbehind and a negative lookahead to only match ms that are not surrounded by brackets. It will work with [mm] but not [mmm] or [mmdd].

Regex.Replace("yyyy[m]mm", @"(?<!\[)m(?!\])", "M")

Upvotes: 1

Related Questions