Extract digits from string - StringUtils Java

前端 未结 18 1236
忘掉有多难
忘掉有多难 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"));
        }
     }
    

提交回复
热议问题