小编典典

如何从C#中的字符串中删除带引号的字符串文字?

algorithm

我有一个字符串:

您好“引号”和“琐碎”的东西世界

并想获得字符串减去引用的部分。例如,

你好,世界

有什么建议?


阅读 449

收藏
2020-07-28

共1个答案

小编典典

resultString = Regex.Replace(subjectString, 
    @"([""'])# Match a quote, remember which one
    (?:      # Then...
     (?!\1)  # (as long as the next character is not the same quote as before)
     .       # match any character
    )*       # any number of times
    \1       # until the corresponding closing quote
    \s*      # plus optional whitespace
    ", 
    "", RegexOptions.IgnorePatternWhitespace);

将适用于您的示例。

resultString = Regex.Replace(subjectString, 
    @"([""'])# Match a quote, remember which one
    (?:      # Then...
     (?!\1)  # (as long as the next character is not the same quote as before)
     \\?.    # match any escaped or unescaped character
    )*       # any number of times
    \1       # until the corresponding closing quote
    \s*      # plus optional whitespace
    ", 
    "", RegexOptions.IgnorePatternWhitespace);

还将处理转义的引号。

这样就可以正确转换

Hello "quoted \"string\\" and 'tricky"stuff' world

进入

Hello and world
2020-07-28