从正则表达式中提取匹配项

时间:2016-06-08 05:31:24

标签: c# .net regex

给定一个字符串

""Being Ordered Around by You Makes Me Really Angry Somehow!!!" "Whaddaya Mean, 'Somehow'!!?""
""Omae ni Meirei Sareru no wa Nanka Haratatsu!!!" "Nankatte Nani!!?""

如何在每组双引号之间提取字符串(包括中间的双引号),以便我得到两个单独的字符串,如:

"Being Ordered Around by You Makes Me Really Angry Somehow!!!" "Whaddaya Mean, 'Somehow'!!?"

"Omae ni Meirei Sareru no wa Nanka Haratatsu!!!" "Nankatte Nani!!?"

我正在使用的正则表达式是"(.*)(.*)",根据此工具,它匹配正常

enter image description here

我的问题是将两个匹配作为单独的字符串提取。

var pattern =  new Regex(@"""(.*)(.*)""", RegexOptions.None);
var matches = pattern.Matches(text);

matches不包含两个元素。我究竟做错了什么?

2 个答案:

答案 0 :(得分:1)

尝试使用Regex.Match代替Matches和此正则表达式

"("[^"]*")[^"]*("[^"]*")"

它匹配"捕获跟随"以及下一个"的所有内容。然后它匹配到下一个"的任何内容。然后重复 - 捕获以下"以及包含下一个"的所有内容。最后它匹配终止"。这两个字符串,包括它们的周围引号,位于捕获组1和1中。 2。

这样的事情:

    string s1 = "\"\"Being Ordered Around by You Makes Me Really Angry Somehow!!!\" \"Whaddaya Mean, 'Somehow'!!?\"\"",
           s2 = "\"\"Omae ni Meirei Sareru no wa Nanka Haratatsu!!!\" \"Nankatte Nani!!?\"\"";

    Console.WriteLine("Before 1  : " + s1);
    Console.WriteLine("Before 2  : " + s2);

    Regex r = new Regex("\"(\"[^\"]*\")[^\"]*(\"[^\"]*\")\"");
    Match m = r.Match(s1);
    Console.WriteLine("After 1.1 : " + m.Groups[1].Value);
    Console.WriteLine("After 1.2 : " + m.Groups[2].Value);

    m = r.Match(s2);
    Console.WriteLine("After 2.1 : " + m.Groups[1].Value);
    Console.WriteLine("After 2.2 : " + m.Groups[2].Value);

See it here at ideone

答案 1 :(得分:0)

您可以尝试this regex

dispatch_sync(dispatch_get_main_queue(), {
    delegate.requestSucceededWithJsonResponse(responseObject!)
});

并迭代MatchCollection类提供的匹配。