# Thread: how to get the Integers out of a String

1. Member
Join Date
Jan 2009
Posts
37
Rep Power
0

## how to get the Integers out of a String

Hi,

I have a string like this

How can I get the 10 and the 5 into seperate variables

e.g.

tailsCount=5

I need to get all the integers out of a String

is it possible?

2. yes, use regular expressions.

take a look at String.matches() in java doc

3. Member
Join Date
Jan 2009
Posts
37
Rep Power
0
I found it but I don't really understand regular Expressions, can anyone give me an example?

4. examples? not me, its a whole chapter by itself.
if only christ was here...

try googleing for it. java regex
here's one:
Lesson: Regular Expressions (The Java™ Tutorials > Essential Classes)

5. Java Code:
```String one="10";
int two=Integer.parseInt(one);```

6. err no. its more like:

and he wants to extract 10 and 5 out of it.

7. Member
Join Date
Jan 2009
Posts
37
Rep Power
0
Figured out a way to do it

String[] arraystring=s.split(" ");
int anint = String[4]; //which will be 10
int anotherint=String[5]; //which will be 5

8. OH its a fixed string. i thought you have a dynamic string.

9. Java Code:
```
public class Numbers {

/**
* @param args
*/
public int[] hasNumber(String s) {
int[] numbs=new int[s.length()];
int count=0;
for (int j = 0;j < s.length();j++) {
if (Character.isDigit(s.charAt(j))){
numbs[count]=Integer.parseInt(Character.toString(s.charAt(j)));
for(int i=j+1;Character.isDigit(s.charAt(i));i++){
j=i;
numbs[count]=numbs[count]*10+Integer.parseInt(Character.toString(s.charAt(j)));

}
count++;
}

}
return numbs;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Numbers().hasNumber("123fdgdf78hj");

}

}```

10. thats a good idea to avoid regex.
actually the string must end w/ a non-digit, otherwise, it'll throw an exception.

11. Here's a way to use a regex to get rid of text. You would then split, as you did, and not have to worry about the position. Given that you are dealing with fixed position, this is unnecessary, but learning regex will save you in a lot of situations.

String workString = s.replaceAll("[^\\d ]", "");
workString = workString.replaceAll("(^ +| +\$"), "");

The first expression removes everything but digits and blanks. Note the the \\d has two backslashes because Java uses backslash as an escape character, the regex only sees \d.

The second expression removes leading and training spaces.

Go to a regex tutorial site and find out what all that mess does. It's a good way to start.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•