2

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.

5
  • substring() and indexOf()? Commented Mar 10, 2013 at 17:49
  • Is this string static? IE. is it always in this format? Commented Mar 10, 2013 at 17:50
  • Adding to Eng.Found - may be a regex with the logic, if you tell us what it is. Commented Mar 10, 2013 at 17:50
  • Hmm the only thing that changes in here is the score. Say the score is 26. And the next score is 7. Commented Mar 10, 2013 at 17:51
  • Hm then parse it till the dot, get the first part, then parse it again according to empty space get the last Commented Mar 10, 2013 at 17:55

3 Answers 3

10

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).
Sign up to request clarification or add additional context in comments.

9 Comments

can you explain a little bit the code you provided? Since I'd like to understand how this works. Thanks.
Okay but it still gets the next characters?
It matches on the remaining characters so that it "knows" where the initial digits are
Strings are immutable. Are you using the newly created firstNumber Sting rather than strScore?
Can't see how you could get that. If you want to add your code to the question...
|
3

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

3 Comments

Hmm, what if the score is only 7?
That will be OK because a space will be ignored afterwards.
well I still disagree, you cant be sure that the integer has less than two digits
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.