【问题标题】:String search using regular expressions使用正则表达式进行字符串搜索
【发布时间】:2011-07-07 08:16:45
【问题描述】:

我正在尝试匹配不包含引号但它们可以包含转义引号的字符串。

当我说字符串时,我的意思是引号和其中的字符串。

我正在使用这个正则表达式,但它不起作用。

\"(?![^\\\\]\")\"

解决方案:

@"""[^""\\\r\n]*(?:\\.[^""\\\r\n]*)*"""

代码(c#)

MatchCollection matches = Regex.Matches(input,@"""[^""\\\r\n]*(?:\\.[^""\\\r\n]*)*""");
        foreach (Match match in matches)
        {
            result += match.Index + " " + match.Value + System.Environment.NewLine ;
        }

【问题讨论】:

    标签: c# .net regex string quotation-marks


    【解决方案1】:

    "[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"

    http://www.regular-expressions.info/examplesprogrammer.html

    请注意,您需要正确转义某些字符(取决于您使用的字符串文字)!以下演示:

    using System;
    using System.Text.RegularExpressions;
    
    class Program
    {
      static void Main()
      {
        string input = "foo \"some \\\" text\" bar";
    
        Match match = Regex.Match(input, @"""[^""\\\r\n]*(?:\\.[^""\\\r\n]*)*""");
    
        if (match.Success)
        {
          Console.WriteLine(input);
          Console.WriteLine(match.Groups[0].Value);
        }
      }
    }
    

    将打印:

    foo "some \" text" 栏
    "一些\"文本"

    【讨论】:

    • @jaywayco,发布不匹配的示例
    • 它应该匹配 this blah\"blah 而不是 this blah"blah
    • @polishchuk,我冒昧地添加了一个基于(工作!)正则表达式的示例。
    • @jaywayco,检查,它将匹配来自"blah"blah""blah\"blah""blah",如果你想验证字符串输入,只需将^放在开头,$放在结尾,例如:^"[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"$,所以它将匹配"blah\"blah",但不匹配"blah"blah"
    • @yossi,这取决于您选择的字符串文字。使用 @"..." 文字时,您只需在 " 前面添加另一个 " 即可转义 ",如运行演示所示。
    【解决方案2】:

    试试这个

    [^"\\]*(?:\\.[^"\\]*)*
    

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 2014-02-08
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多