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
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);
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);
}
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]))
Just one line:
int value = Integer.parseInt(string.replaceAll("[^0-9]", ""));
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"));
}
Use this code numberOnly will contain your desired output.
String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");