有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何删除逗号后的两位数或一位数以及逗号后的剩余字符?正则表达式

我有一些数字列表:
1000000,00
1000000,0
100000000
100000000

预期输出:
1000000
1000000
100000000
一,

因此,当最后一个逗号后只有两个数字和一个数字时,该数字将不会被程序保存,而被忽略。那么,当我想保存输入时,我该如何处理这个问题呢

例如,我目前的想法:

textField1.getText().{someCodeToRemoveTwoOrOneDigit}

共 (1) 个答案

  1. # 1 楼答案

    您可以编写一个助手方法,通过将字符串拆分为逗号来实现这一点:

    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);
     }
    }
    

    这是未经测试,但结构应该是好的