Extract digits from string - StringUtils Java

前端 未结 18 1082
忘掉有多难
忘掉有多难 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:15

    I've created a JUnit Test class(as a additional knowledge/info) for the same issue. Hope you'll be finding this helpful.

       public class StringHelper {
        //Separate words from String which has gigits
            public String drawDigitsFromString(String strValue){
                String str = strValue.trim();
                String digits="";
                for (int i = 0; i < str.length(); i++) {
                    char chrs = str.charAt(i);              
                    if (Character.isDigit(chrs))
                        digits = digits+chrs;
                }
                return digits;
            }
        }
    

    And JUnit Test case is:

     public class StringHelperTest {
        StringHelper helper;
    
            @Before
            public void before(){
                helper = new StringHelper();
            }
    
            @Test
        public void testDrawDigitsFromString(){
            assertEquals("187111", helper.drawDigitsFromString("TCS187TCS111"));
        }
     }
    
    0 讨论(0)
  • 2020-12-01 09:16

    try this :

    String s = "helloThisIsA1234Sample";
    s = s.replaceAll("\\D+","");
    

    This means: replace all occurrences of digital characters (0 -9) by an empty string !

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

    You can also use java.util.Scanner:

    new Scanner(str).useDelimiter("[^\\d]+").nextInt()

    You can use next() instead of nextInt() to get the digits as string.

    You can check for the presence of number using hasNextInt() on the Scanner.

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

    Try this approach if you have symbols and you want just numbers:

        String s  = "@##9823l;Azad9927##$)(^738#";
        System.out.println(s=s.replaceAll("[^0-9]", ""));
        StringTokenizer tok = new StringTokenizer(s,"`~!@#$%^&*()-_+=\\.,><?");
        String s1 = "";
        while(tok.hasMoreTokens()){
            s1+= tok.nextToken();
        }
        System.out.println(s1);
    
    0 讨论(0)
  • 2020-12-01 09:18

    You can use the following regular expression.

    string.split(/ /)[0].replace(/[^\d]/g, '')
    
    0 讨论(0)
  • 2020-12-01 09:21
       `String s="as234dfd423";
    for(int i=0;i<s.length();i++)
     {
        char c=s.charAt(i);``
        char d=s.charAt(i);
         if ('a' <= c && c <= 'z')
             System.out.println("String:-"+c);
         else  if ('0' <= d && d <= '9')
               System.out.println("number:-"+d);
        }
    

    output:-

    number:-4
    number:-3
    number:-4
    String:-d
    String:-f
    String:-d
    number:-2
    number:-3
    
    0 讨论(0)
提交回复
热议问题