我正在使用正则表达式来解析 OCR 文档中的数据,并且我正在努力匹配 1000 个逗号分隔符被误读为点的场景,以及点被误读为逗号的场景!
因此,如果真实值为 1234567.89,则打印为 1,234,567.89,但被误读为:
1.234,567.89
1,234.567.89
1,234,567,89
等等
我可能可以在 C# 中对此进行排序,但我确信正则表达式可以做到这一点。任何正则表达式向导可以提供帮助吗?
更新:
我意识到这是一个非常愚蠢的问题,因为正则表达式非常直接地捕获所有这些,这就是我选择解释匹配的方式。这将在 C# 中。谢谢 - 很抱歉在此浪费您的时间!
我会将答案标记为 Dmitry,因为它接近我正在寻找的内容。谢谢。
最佳答案
请注意,存在歧义,因为:
123,456 // thousand separator
123.456 // decimal separator
两者都可以(123456
和 123.456
)。但是,我们可以检测到一些情况:
- 小数分隔符太多
123.456.789
- 订单错误
123.456,789
- 数字计数错误
123,45
所以我们可以设置一个规则:分隔符可以为十进制 1,如果它是最后一位并且后面没有正好三位数字(参见上面的歧义),所有 其他分隔符应视为千位:
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
关于c# - 用于十进制数字点而不是逗号的正则表达式 (.NET),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37257745/