【发布时间】:2012-01-17 23:34:24
【问题描述】:
我尝试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 是唯一产生意外结果的方法(它在无效位置上分裂!)!Matches 和 Replace 都给出绝对正确的结果。我什至尝试在 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
【问题讨论】:
-
我会尝试包括它们..它们很大
-
我认为您的模式是错误的(不要问我如何正确处理),因为您的代码似乎跳过了字符串的一部分然后拆分。您的替换和匹配方法也是如此,但这些是不可见的(替换代码时可能会跳过您的字符串替换内容,但输出很好)
-
您是否阅读过 documentation 中讨论捕获括号的评论 - 尤其是存在多个捕获括号的行为?
-
@Marnix van Valen 正如我所提到的,我已经用 RegexBuddy 检查了正则表达式。
-
@Damien_The_Unbeliever 谢谢,我会看评论