I need to extract the first integer found in a java.lang.String
and am unsure as to whether to try and use a substring
approach or a regex approach:
// Want to extract the 510 into an int.
String extract = "PowerFactor510";
// Either:
int num = Integer.valueof(extract.substring(???));
// Or a regex solution, something like:
String regex = "\\d+";
Matcher matcher = new Matcher(regex);
int num = matcher.find(extract);
So I ask:
- Which type of solution is more appropriate here, and why?; and
- If the substring approach is more appropriate, what could I use to indicate the beginning of a number?
- Else, if the regex is the appropriate solution, what is the regex/pattern/matcher/method I should use to extract the number?
Note: The string will always begin with the word PowerFactor
followed by a non-negative integer. Thanks in advance!