请注意,这有歧义因为:
123,456 // thousand separator
123.456 // decimal separator
都是可能的(123456
和123.456
)。但是,我们可以检测到一些情况:
- 太多的小数点分隔符
123.456.789
- 错误的顺序
123.456,789
- 错误的数字计算
123,45
因此,我们可以建立一个规则:分隔能为十进制其中一个如果是最后一个一个而不是跟随个恰好三位数(见上歧义),所有 其他分隔符应被视为千元的:
1?234?567?89
^^^
| | the last one, followed by two digits (not three), thus decimal
| not the last one, thus thousand
not the last one, thus thousand
现在让我们来实现常规
private static String ClearUp(String value) {
String[] chunks = value.Split(',', '.');
// No separators
if (chunks.Length <= 1)
return value;
// Let's look at the last chunk
// definitely decimal separator (e.g. "123,45")
if (chunks[chunks.Length - 1].Length != 3)
return String.Concat(chunks.Take(chunks.Length - 1)) +
"." +
chunks[chunks.Length - 1];
// may be decimal or thousand
if (value[value.Length - 4] == ',')
return String.Concat(chunks);
else
return String.Concat(chunks.Take(chunks.Length - 1)) +
"." +
chunks[chunks.Length - 1];
}
现在让我们尝试一些测试:
String[] data = new String[] {
// you tests
"1.234,567.89",
"1,234.567.89",
"1,234,567,89",
// my tests
"123,456", // "," should be left intact, i.e. thousand separator
"123.456", // "." should be left intact, i.e. decimal separator
};
String report = String.Join(Environment.NewLine, data
.Select(item => String.Format("{0} -> {1}", item, ClearUp(item))));
Console.Write(report);
结果是
1.234,567.89 -> 1234567.89
1,234.567.89 -> 1234567.89
1,234,567,89 -> 1234567.89
123,456 -> 123456
123.456 -> 123.456
你想捕捉什么,错误的或正确的? –
对不起,当然。我实际上想要捕获所有这些包括缺少1000个逗号分隔符的文件。所以我可能自己回答了这个问题,这根本不是真正的正则表达式问题。卫生署。 –
我认为如果你不知道号码应该是什么,这个问题是不可行的。你如何判断解释“,”或“是否正确”。 ? –