Regex.Split()奇怪的行为

时间:2012-01-17 14:19:29

标签: c# .net regex

我尝试following regex在文本文件中拆分数据,但我在测试过程中发现了一个奇怪的错误 - 非常简单的文件显然是错误的。用于说明此类行为的示例代码:

        const string line = "511525,3122,9,39,2007,9,39,3127,9,39,\" -49,368.11 \",\"-32,724.16\",2,1,\" 2,347.91 \", -   ,\" 2,234.17 \", -   ,2.2,1.143,2,1.24,FALSE,1,2,0,311,511625";
        const string pattern = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";

        Console.WriteLine();
        Console.WriteLine("SPLIT");
        var splitted = Regex.Split(line, pattern, RegexOptions.Compiled);
        foreach (var s in splitted)
        {
            Console.WriteLine(s);
        }

        Console.WriteLine();
        Console.WriteLine("REPLACE");
        var replaced = Regex.Replace(line, pattern, "!" , RegexOptions.Compiled);
        Console.WriteLine(replaced);

        Console.WriteLine();
        Console.WriteLine("MATCH");
        var matches = Regex.Matches(line, pattern);
        foreach (Match match in matches)
        {
            Console.WriteLine(match.Index);
        }

因此,正如您所看到的,split是唯一产生意外结果的方法(它在无效位置上分裂!)!MatchesReplace都给出了绝对正确的结果。我甚至试图在RegexBuddy中测试提到的正则表达式,它显示与Regex.Matches相同的匹配! 我错过了什么或看起来像Split方法中的错误?

控制台输出

SPLIT
511525
, -   ," 2,234.17 "
3122
, -   ," 2,234.17 "
9
, -   ," 2,234.17 "
39
, -   ," 2,234.17 "
2007
, -   ," 2,234.17 "
9
, -   ," 2,234.17 "
39
, -   ," 2,234.17 "
3127
, -   ," 2,234.17 "
9
, -   ," 2,234.17 "
39
, -   ," 2,234.17 "
" -49,368.11 "
, -   ," 2,234.17 "
"-32,724.16"
, -   ," 2,234.17 "
2
, -   ," 2,234.17 "
1
, -   ," 2,234.17 "
" 2,347.91 "
 -   ," 2,234.17 "
 -
" 2,234.17 "
" 2,234.17 "
 -
2.2
1.143
2
1.24
FALSE
1
2
0
311
511625

REPLACE
511525!3122!9!39!2007!9!39!3127!9!39!" -49,368.11 "!"-32,724.16"!2!1!" 2,347.91 "! -   !" 2,234.17 "! -   !2.2!1.143!2!1.24!FALSE!1!2!0!311!511625

MATCH
6
11
13
16
21
23
26
31
33
36
51
64
66
68
81
87
100
106
110
116
118
123
129
131
133
135
139

2 个答案:

答案 0 :(得分:2)

Solution from MS

(添加ExplicitCapture正则表达式选项)

答案 1 :(得分:2)

根据您对Microsoft的回复(添加ExplicitCapture),问题似乎是捕获组。 ExplicitCapture选项会将捕获组变为非捕获组

通过使组明确不捕获,您可以在没有选项的情况下执行相同的操作:

const string pattern = ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)";

其中,用LINQPad测试,似乎产生的结果正在寻找。

是否有任何捕获组产生差异,如docs中针对Regex.Split所述

  

如果在Regex.Split表达式中使用捕获括号,则为any   捕获的文本包含在结果字符串数组中。例如,   将字符串“plum-pear”分开放置在捕获内的连字符上   括号添加一个包含连字符的字符串元素   返回数组。