2

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

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

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

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

解决方案:

@"""[^""\\\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 ;
        }
4

2 回答 2

6

"[^"\\\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 "一些\" 文本" 栏
“一些\”文本”
于 2011-07-07T08:20:59.080 回答
2

试试这个

[^"\\]*(?:\\.[^"\\]*)*
于 2011-07-07T08:30:47.523 回答