使用正则表达式替换字符,但不要替换转义字符

时间:2013-04-11 07:00:38

标签: c# regex replace escaping

我有一个字符串,我希望使用Regex[替换为{,但如果[被转义,请忽略它,如下所示:

abc[def\[ghi

abc{def\[ghi

我该怎么做?非常感谢你!

1 个答案:

答案 0 :(得分:3)

使用此:

Regex regexObj = new Regex(
    @"(?<=     # Make sure that this is true before the start of the match:
     (?<!\\)   # There is no single backslash,
     (?:\\\\)* # but if there are backslashes, they need to be an even number.
    )          # End of lookbehind assertion.
    \[         # Only then match a bracket", 
    RegexOptions.IgnorePatternWhitespace);