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

3

我有一个字符串:

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

想要得到去掉引号部分的字符串,例如:

Hello and world

有什么建议吗?


2
你需要支持转义引号吗?此外,这似乎是一个无用的练习 - 这应该被标记为作业吗? - Kirk Woll
4
“Don't stop believin' hold on to the feelin' streetlight people”这句话的“believin'”和“feelin'”是否应该被视为内部引用的分隔符?“don't”中的撇号又该怎么处理?此外,需要考虑“圆引号”吗,还是只需要考虑“直引号”?我的建议是:在编写任何代码之前,请编写非常谨慎和详细的规范 - Eric Lippert
@Eric。谢谢,但是已经有一个语法检查器来确保引号平衡了。 - Andrew White
1
@Andrew White:在你的例子中,引号不平衡。 - Matt Ellen
@Andrew,“我简直不敢相信他不相信我。”引号平衡了,你只剩下“我不能相信我自己。” - Anthony Pegram
显示剩余6条评论
3个回答

8
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

我正打算用 var "\"[^\"]*\"" 作为我的正则表达式字符串(即 "[^"]*" 作为正则表达式)。您能解释一下您的正则表达式是如何工作的以及为什么吗? - Domenic

1
使用正则表达式匹配任何带引号的字符串,并将它们替换为空字符串。使用Regex.Replace()方法进行模式匹配和替换。

0
如果像我一样,你害怕正则表达式,那么我已经根据你的示例字符串提供了一种功能性的方法来完成它。可能有一种方法可以使代码更短,但我还没有找到它。
private static string RemoveQuotes(IEnumerable<char> input)
{
    string part = new string(input.TakeWhile(c => c != '"' && c != '\'').ToArray());
    var rest = input.SkipWhile(c => c != '"' && c != '\'');
    if(string.IsNullOrEmpty(new string(rest.ToArray())))
        return part;
    char delim = rest.First();
    var afterIgnore = rest.Skip(1).SkipWhile(c => c != delim).Skip(1);
    StringBuilder full = new StringBuilder(part);
    return full.Append(RemoveQuotes(afterIgnore)).ToString();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接