Reputation: 1148
Seeking regex experts here. I have a string that has numbers in it such as
abc 2 de fdfg 3 4 fdfdfv juk @ dfdfgd 45
I need to find all the numbers from such string and sum it up.
My Java code is as follows:
public static void main(String[] args) {
String source = " abc 2 de fdfg 3 4 fdfdfv juk @ dfdfgd 45";
Pattern pattern = Pattern.compile("[\\w*\\W*(\\d*)]+");
Matcher matcher = pattern.matcher(source);
if (matcher.matches()) {
System.out.println("Matched");
// For loop is not executed since groupCount is zero
for (int i=0; i<matcher.groupCount(); i++) {
String group = matcher.group(i);
System.out.println(group);
}
} else {
System.out.println("Didn't match");
}
}
So matcher.matches() returns true, and therefore I can see that "Matched" getting printed. However, when I try to get the groups, expecting numbers, nothing gets printed.
Can someone please point to me what is wrong with my regex and grouping part?
Upvotes: 0
Views: 129
Reputation: 442
String[] arr=source.split("\\d+");
int sum=0;
for(String x : arr) {
int n=0;
try {
n=Integer.parseInt(x);
} catch(NumberFormatException nfe){}
sum+=n;
}
System.out.println("Sum: "+sum);
Upvotes: -1
Reputation: 9041
Just extract the digits out in groups and not worry about the white spaces.
public static void main(String[] args) throws Exception {
String source = " abc 2 de fdfg 3 4 fdfdfv juk @ dfdfgd 45";
// "\\d+" will get all of the digits in the String
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(source);
int sum = 0;
// Convert each find to an Integer and accumulate the total
while (matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
System.out.println("Sum: " + sum);
}
Results:
Sum: 54
Upvotes: 2