Extract digits from string - StringUtils Java

前端 未结 18 1084
忘掉有多难
忘掉有多难 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:31
            String line = "This order was32354 placed for QT ! OK?";
            String regex = "[^\\d]+";
    
            String[] str = line.split(regex);
    
            System.out.println(str[1]);
    
    0 讨论(0)
  • 2020-12-01 09:31

    You can use the following Code to retain Integers from String.

    String text="Hello1010";
    System.out.println(CharMatcher.digit().retainFrom(text));
    

    Will give you the Following Output

    1010

    0 讨论(0)
  • 2020-12-01 09:32

    Use a regex such as [^0-9] to remove all non-digits.

    From there, just use Integer.parseInt(String);

    0 讨论(0)
  • 2020-12-01 09:34

    You can try this:

      String str="java123java456";
      String out="";
      for(int i=0;i<str.length();i++)
      {
        int a=str.codePointAt(i);
         if(a>=49&&a<=57)
           {
              out=out+str.charAt(i);
           }
       }
     System.out.println(out);
    
    0 讨论(0)
  • 2020-12-01 09:36

    You can use str = str.replaceAll("\\D+","");

    0 讨论(0)
  • 2020-12-01 09:37

    I always like using Guava String utils or similar for these kind of problems:

    String theDigits = CharMatcher.inRange('0', '9').retainFrom("abc12 3def"); // 123
    
    0 讨论(0)
提交回复
热议问题