2013-04-11 105 views
2

我有一個字符串,我想用Regex更換[{,但如果[被轉義,忽略它,就像這樣:使用正則表達式替換字符,但不代替轉義字符

abc[def\[ghi 

abc{def\[ghi 

我該怎麼做?非常感謝你!

+1

請問[要替換之前總是它有一個空間?如果是這樣,只需用「{」替換「[」。 – 2013-04-11 07:01:37

+0

不,只是例子 – Sakura 2013-04-11 07:02:41

+0

這真的是真正的規則嗎?該規則不應該是「用括號替換未轉義的括號」嗎? – 2013-04-11 07:03:46

回答

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); 
+2

+1是的,這應該很好:-) – sloth 2013-04-11 07:25:56

+0

謝謝,它工作正常:) – Sakura 2013-04-11 07:32:05