What are the best practices in java for extracting number from text and parse it?
for example:
String s = "Availability in 20 days";
Please don't stick just to the example I am looking for a good general practice and scenarios.
Thank you.
What are the best practices in java for extracting number from text and parse it?
for example:
String s = "Availability in 20 days";
Please don't stick just to the example I am looking for a good general practice and scenarios.
Thank you.
Using regular expression:
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("Availability in 20 days");
while (m.find()) {
int number = Integer.parseInt(m.group());
...
}
I am not sure of the best practices, but one way that I would do it described in this stack overflow questions.
How to extract numbers from a string and get an array of ints?
I'm not exactly sure what you want to do, but here are some solutions that might help you:
List item use .indexOf and .substring to find numbers in the string
example:
String s;
String str = new String("1 sentence containing 5 words and 3 numbers.");
ArrayList<Integer> integers = new ArrayList<Integer>();
for (int i = 0; i <= 9; i++) {
int start = 0;
while (start != -1) {
String sub = str.substring(start);
int x = sub.indexOf(i);
if (x != -1) {
s = sub.substring(x, x+1);
integers.add(Integer.parseInt(s));
start = x;
} else {
//number not found
start = -1;
}
}
}
extract one character at a time and try to parse it, if there's no exception, it is a number. I DEFINITELY DON'T RECOMMEND THIS SOLUTION, but it should also work. Unfortunately, I can't tell you which method is quicker, but I can imagine that - although there are fewer commands - the second version is slower, considering that there's several exceptions thrown.
String s;
int integ;
ArrayList<Integer> integers = new ArrayList<Integer>();
String str = new String("1 sentence containing 5 words and 3 numbers.");
for (int i = 0; i < str.length(); i++) {
s = str.substring(i,i+1);
try {
integ = Integer.parseInt(s);
integers.add(integ);
} catch (NumberFormatException nfe) {
//nothing
}
}
if there are serveral numbers then
String[] after = str.replaceAll("\\D+", " ").split("\\s+");