【问题标题】:Use Regex replace character but dont replace escaped character使用正则表达式替换字符但不替换转义字符
【发布时间】:2013-04-03 06:43:28
【问题描述】:

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

abc[def\[ghi

abc{def\[ghi

我该怎么做?非常感谢!

【问题讨论】:

  • 您要替换的 [ 之前是否总是有空格?如果是这样,只需将“[”替换为“{”即可。
  • 这真的是实际规则吗?规则不应该是“用大括号替换未转义的括号”吗?
  • 另外,像[foo] bar {baz\[bam} 这样的字符串呢?你真的希望结果是{foo] bar {baz\[bam}吗?
  • 这个[abc[efg[hij 怎么样.. 应该是:{abc{efg[hij 还是只替换第一个,所以它变成{abc[efg[hij
  • @MohamedTarek:我想全部替换,TimPietzcker 给了我正确的解决方案!谢谢

标签: c# regex replace escaping


【解决方案1】:

使用这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2015-11-30
    相关资源
    最近更新 更多