这是一个正则表达式解决方案,它允许在文本的引用部分中使用转义分隔符。如果您更喜欢 *nix 反斜杠样式的转义,只需将正则表达式的适当部分 , 替换('')
为(\\')
.
static readonly Regex rxQuotedStringLiteralPattern = new Regex(@"
# A quoted string consists of
' # * a lead-in delimiter, followed by
(?<content> # * a named capturing group representing the quoted content
( # which consists of either
[^'] # * an ordinary, non-delimiter character
| # OR
('') # * an escape sequence representing an embedded delimiter
)* # repeated zero or more times.
) # The quoted content is followed by
' # * the lead-out delimiter
"
, RegexOptions.ExplicitCapture|RegexOptions.IgnorePatternWhitespace
) ;
public static IEnumerable<string> ParseQuotedLiteralsFromStringUsingRegularExpressions( string s )
{
for ( Match m = rxQuotedStringLiteralPattern.Match( s ?? "" ) ; m.Success ; m = m.NextMatch() )
{
string raw = m.Groups[ "content" ].Value ;
string cooked = raw.Replace( "''" , "'" ) ;
yield return cooked ;
}
}