C#:正则表达式用于包含单引号的字符串(并通过加倍引号来转义)

时间:2013-01-21 09:08:28

标签: c# regex string escaping

我没有找到问题的正则表达式。总有一个示例正则表达式用于反斜杠转义。

但我需要通过加倍封闭字符来逃避。

示例:'o''reilly'

结果:o'reilly

1 个答案:

答案 0 :(得分:3)

'(?:''|[^']*)*'

将匹配引号分隔的字符串,该字符串可能包含双重转义引号。这就是你的正则表达式找到那些字符串。

<强>解释

'      # Match a single quote.
(?:    # Either match... (use (?> instead of (?: if you can)
 ''    # a doubled quote
|      # or
[^']*  # anything that's not a quote
)*     # any number of times.
'      # Match a single quote.

现在要正确删除引号,您可以分两步完成:

首先,搜索(?<!')'(?!')以查找所有单引号;没有任何东西替换它们。

<强>解释

(?<!') # Assert that the previous character (if present) isn't a quote
'      # Match a quote
(?!')  # Assert that the next character (if present) isn't a quote

其次,搜索''并将所有内容替换为'