Extract digits from string - StringUtils Java

蹲街弑〆低调 提交于 2019-11-27 12:59:17

Use this code numberOnly will contain your desired output.

   String str="sdfvsdf68fsdfsf8999fsdf09";
   String numberOnly= str.replaceAll("[^0-9]", "");
Michael Bavin

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

String theDigits = CharMatcher.inRange('0', '9').retainFrom("abc12 3def"); // 123

Just one line:

int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));

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.

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

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

try this :

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

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

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

You can use the following regular expression.

string.split(/ /)[0].replace(/[^\d]/g, '')
        String line = "This order was32354 placed for QT ! OK?";
        String regex = "[^\\d]+";

        String[] str = line.split(regex);

        System.out.println(str[1]);

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

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

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

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

}
Amol Nile
   `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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!