在文本中查找数字并将它们相加 [英] Finding numbers in a text and summing them

查看:128
本文介绍了在文本中查找数字并将它们相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里寻求正则表达式专家。我有一个包含数字的字符串,例如

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.

我的Java代码如下:

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");
    }
}

所以matcher.matches()返回true,因此我可以看到匹配打印。然而,当我试图获得群组时,期待数字,没有任何内容被打印出来。

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?

推荐答案

只需在组中提取数字,不用担心空格。

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);
}

结果:


总和:54

Sum: 54

这篇关于在文本中查找数字并将它们相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆