【问题标题】:How can I remove quoted string literals from a string in C#?如何从 C# 中的字符串中删除带引号的字符串文字?
【发布时间】:2010-12-16 15:53:23
【问题描述】:

我有一个字符串:

你好“带引号的字符串”和“棘手的东西”世界

并希望得到减去引号部分的字符串。例如,

你好,世界

有什么建议吗?

【问题讨论】:

  • 好的,所以引用的字符串可以包含“其他”引用符号。也可以有"This is \"one\" string"之类的转义引号吗?
  • 是否需要支持转义引号字符?此外,这似乎是一种无用的练习——是否应该将其标记为作业?
  • @Kirk,我今年 37 岁,很久以前就放弃了作业。抱歉,如果我的问题没有达到您的高标准。
  • “不要停止相信'坚持感觉'街灯人”怎么样? "believin'" 和 "feelin'" 上缺少的 gs 是否被视为界定内部引用? “不要”中的撇号呢?另外,您需要考虑“圆引号”还是“直引号”?我的建议:在编写任何代码之前,编写一个非常仔细和详细的规范
  • @Andrew White:在你的例子中,引号不平衡

标签: c# algorithm string


【解决方案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

【讨论】:

  • 我只是用 var "\"[^\"]*\"" 作为我的正则表达式字符串(即"[^"]*" 作为正则表达式)输入了类似的内容。你能解释一下你在做什么以及为什么吗?
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    如果您像我一样害怕正则表达式,我已经根据您的示例字符串组合了一种功能性的方法来做到这一点。可能有一种方法可以使代码更短,但我还没有找到。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2011-05-12
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 2020-07-10
      相关资源
      最近更新 更多