請注意,這有歧義因爲:
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個逗號分隔符的文件。所以我可能自己回答了這個問題,這根本不是真正的正則表達式問題。衛生署。 –
我認爲如果你不知道號碼應該是什麼,這個問題是不可行的。你如何判斷解釋「,」或「是否正確」。 ? –