c# - 如何标记空格和引号字符串,处理转义?

标签 c# regex

我需要标记一个字符串,这样标记可以是:

  1. 双引号内
  2. 空格分隔

带引号的字符串必须处理转义:this: "is included in\"single token\"" 应该变成这样:

[this:] [is included in "single token"]

或者这个:

[this:] [is included in \"single token\"]

( token 是@"[^\s]",不是@"\w")

我见过很多部分问题的解决方案:

  • 找到所有带引号的字符串 - 但会留下所有未带引号的标记
  • 找到所有不带引号的标记——遗漏带引号的字符串

不幸的是,我找不到将这两个问题的解决方案融合在一起的方法...


这是我目前所拥有的:

static void Main(string[] args) {
    var inputs = new List<string>
        {
            @"bef\`ore`xy z`after",
            @"start `with simple` expression: `i am xprsion` and this is empty: `` ...",
            @"now       `with       some    tabs`       expression",
            @"nothing \but\ escapers\\\",
            @"some  #@   other   kind$    of    whildcards...",
            @"and now `with \`allegedly\` escape` char",
            @"tight`  or even   `connected",
        }.Select(s => s.Replace('`', '"'));

    var sections = new[]
        {
            @"(?<i>[^\s]+)",
            @"((?<!\\)`(?<i>.*?)(?<!\\)`)", // quoted
        };

    var pattern = string.Join("|", sections).Replace("`","\"");

    foreach (var i in inputs)
    {
        Regex.Matches(i, pattern)
             .Cast<Match>()
             .Select(m => m.Groups["i"].Value)
             .ToList()
             .ForEach(s => Console.Write("[{0}]", s));

        Console.WriteLine();
    }

    Console.ReadKey();
}

但是引用模式和空白分隔模式的结合破坏了这一切......

最佳答案

您可以使用此正则表达式进行匹配

(?<=[^\\]|^)".*?(?<=[^\\])"|(\\"|[\w])+

不要忘记使用 "" 转义 " 并使用逐字字符串 @

 Regex.Matches(input,yourRegex)
      .Cast<Match>()
      .Select(x=>x.Value)
      .ToList();

Demo {你不能在此处更改输入,打开该站点的新实例}

关于c# - 如何标记空格和引号字符串,处理转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17388671/

相关文章:

c# - 如何合并数据表中的数据

c# - 如何验证本地化是否在 Bot 框架中正常工作

JavaScript 正则表达式获取两个短语之间的分隔匹配

JavaScript。如何从字符串中提取 URI 编码的电子邮件?

混合字符串中超过 10 位数字的正则表达式?

c# - 如何编辑 .csproj 文件

c# - 用完全相同的代码合并 catch block ?

c# - 比较 2 个字符串时如何将一个值替换为另一个值?

java - 匹配器: "No match found..."

regex - Postgres : regexp_replace & trim