我有一些数字列表:
1,000,000,00
1,000,000,0
10亿个
1,00,0000,000
预期产量:
百万
百万
10亿个
1
因此,当最后一个逗号后面只有两位数字和一位数字时,该数字将不会被程序保存,只是省略了。那么,当我想保存输入时,我该怎么处理这个问题?
例如我目前的想法:
textField1.getText().{someCodeToRemoveTwoOrOneDigit}
答案 0 :(得分:1)
使用正则表达式,例如"^(.*),[\\d]{1,2}$"
public static void main(String[] args)
{
String[] inp = { "1,000,000,00", "1,000,000,0", "1,000,000", "1,000,000,000" };
for (String s : inp) {
System.out.println(s+ " : " + s.replaceAll("^(.*),[\\d]{1,2}$", "$1"));
}
}
示例输出:
1,000,000,00:1,000,000
1,000,000,0:1,000,000
1,000,000:1,000,000
1,000,000,000:1,000,000,000
答案 1 :(得分:1)
如果您只想删除一个尾随的1位或2位数字块,请执行以下操作:
text.replaceAll(",\\d{1,2}$", "")
1,000,000,00 -> 1,000,000
1,000,000,0 -> 1,000,000
1,000,000,000 -> 1,000,000,000
1,00,000,000 -> 1,00,000,000
$1,00,000,000 -> $1,00,000,000
如果您只想保留一个“有效”号码,即一个包含1-3个前导数字的数字,后跟X个3位数字块,则执行以下操作:
text.replaceAll("\\D*(\\d{1,3}(?:,\\d{3})*)?.*", "$1")
1,000,000,00 -> 1,000,000
1,000,000,0 -> 1,000,000
1,000,000,000 -> 1,000,000,000
1,00,000,000 -> 1
$1,00,000,000 -> 1
答案 2 :(得分:0)
您可以编写一个辅助方法,通过在逗号周围分割字符串来完成此操作:
public String removeLastDigits(String toTrim) {
//split up the string based on commas
String[] trimSplit = toTrim.split(",");
String toRet = "";
//loop over every element but the last
for (int i = 0; i < trimSplit.length() - 1; i++) {
toRet = toRet + trimSplit[i];
toRet = toRet + ",";
}
//add the last element only if it has more than 2 digits
String lastElement = trimSplit[trimSplit.length() - 1];
if (lastElement.length() > 2) {
//return with the last element
return (toRet + lastElement);
} else {
//strip off the end comma and return
return toRet.substring(0, toRet.length() - 1);
}
}
这是未经测试但结构应该很好。