Reputation:
I'd like to get the integer value from my string. Below is my example.
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
But I just want to get the score which is 10. How can I do this?
UPDATED:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
bfLog.createEntry( firstNumber );
I save this to sqlite database.
Upvotes: 2
Views: 31155
Reputation: 1417
You can try this:
String strScore = "Your score is 10. Probability in the next 2 years is 40%";
String intIndex = strScore.valueOf(10);
String intIndex = 10 // Result
Upvotes: 1
Reputation: 159784
You can use one of the String
regex replace
methods to capture the first digits in a captured group:
String firstNumber = strScore.replaceFirst(".*?(\\d+).*", "$1");
.*?
consumes initial non-digits(non-greedy)(\\d+)
Get the one or more available digits in a group!.*
Everything else (greedy).Upvotes: 10
Reputation: 7026
This depends on whether anything else can change in your string.
If it's always the same apart from the number, you can use
int score = Integer.parseInt(strScore.substring(14,16))
because the digits "10" are at index 14 and 15 of the string. If other stuff changes in your string, you should use a regular expression :
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
Upvotes: 3