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
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"));
}
}
try this :
String s = "helloThisIsA1234Sample";
s = s.replaceAll("\\D+","");
This means: replace all occurrences of digital characters (0 -9) by an empty string !
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.
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 use the following regular expression.
string.split(/ /)[0].replace(/[^\d]/g, '')
`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