Extract digits from string - StringUtils Java

前端 未结 18 1083
忘掉有多难
忘掉有多难 2020-12-01 09:06

I have a String and I want to extract the (only) sequence of digits in the string.

Example: helloThisIsA1234Sample. I want the 1234

It\'s a given that the s

相关标签:
18条回答
  • 2020-12-01 09:24

    Extending the best answer for finding floating point numbers

           String str="2.53GHz";
           String decimal_values= str.replaceAll("[^0-9\\.]", "");
           System.out.println(decimal_values);
    
    0 讨论(0)
  • 2020-12-01 09:27

    A very simple solution, if separated by comma or if not separated by comma

    public static void main(String[] args) {
    
        String input = "a,1,b,2,c,3,d,4";
        input = input.replaceAll(",", "");
    
        String alpha ="";
        String num = "";
    
        char[] c_arr = input.toCharArray();
    
        for(char c: c_arr) {
            if(Character.isDigit(c)) {
                alpha = alpha + c;
            }
            else {
                num = num+c;
            }
        }
    
        System.out.println("Alphabet: "+ alpha);
        System.out.println("num: "+ num);
    
    }
    
    0 讨论(0)
  • 2020-12-01 09:27

    Simple python code for separating the digits in string

      s="rollnumber99mixedin447"
      list(filter(lambda c: c >= '0' and c <= '9', [x for x in s]))
    
    0 讨论(0)
  • 2020-12-01 09:28

    Just one line:

    int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));
    
    0 讨论(0)
  • 2020-12-01 09:28

    You can split the string and compare with each character

    public static String extractNumberFromString(String source) {
        StringBuilder result = new StringBuilder(100);
        for (char ch : source.toCharArray()) {
            if (ch >= '0' && ch <= '9') {
                result.append(ch);
            }
        }
    
        return result.toString();
    }
    

    Testing Code

        @Test
        public void test_extractNumberFromString() {
        String numberString = NumberUtil.extractNumberFromString("+61 415 987 636");
        assertThat(numberString, equalTo("61415987636"));
    
        numberString = NumberUtil.extractNumberFromString("(02)9295-987-636");
        assertThat(numberString, equalTo("029295987636"));
    
        numberString = NumberUtil.extractNumberFromString("(02)~!@#$%^&*()+_<>?,.:';9295-{}[=]987-636");
        assertThat(numberString, equalTo("029295987636"));
    }
    
    0 讨论(0)
  • 2020-12-01 09:30

    Use this code numberOnly will contain your desired output.

       String str="sdfvsdf68fsdfsf8999fsdf09";
       String numberOnly= str.replaceAll("[^0-9]", "");
    
    0 讨论(0)
提交回复
热议问题