用正则表达式捕获数字

时间:2014-06-17 19:25:14

标签: java regex

我有这些包含数字组的字符串。我需要做的是捕获每组数字并为它们创建新的字符串。例如,在字符串中:“60 32 28 Some Characters 0 0 0”我需要捕获并将60,32,28,0,0,0放入单独的字符串中。以下是我已经尝试过的一些代码:

public class First {

public static void main(String[] args) {

    String one = "60 32 28 Some Characters 0 0 0";


    Pattern a = Pattern.compile("[0-9]{2}.*?([0-9]{2}).*?([0-9]{2})");      
    Matcher b = a.matcher(one);
    b.find();

    String work = b.group();
    String work1 = b.group(1);
    String work2 = b.group(2);

    System.out.println("this is work: " + work);
    System.out.println("this is work1: " + work1);
    System.out.println("this is work2: " + work2);

    Pattern c = Pattern.compile("([0-9]{2})|([0-9])");      
    Matcher d = c.matcher(one);
    d.find();

    String work3 = d.group();
    System.out.println(work3);



}

}

但是,我无法捕捉每一个数字。我已经浏览了其他教程,但我无法找到我的正则表达式错误,或者除了使用正则表达式之外还有其他解决方案。我没有使用子串,因为数字之间的文本通常长度不同。任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:8)

String[] strings = one.split("[^\\d]+");

这会将一个或多个非数字的每个序列视为分隔符,并返回结果数组。几乎就是你想要的,对吗?

这也有效,但我通常会忘记内置的角色类,这意味着"不是" (谢谢,@Pshemo):

String[] strings = one.split("\\D+");

一个警告:Strings的第一个元素可能是一个空字符串。如果第一个字符不是数字,则会发生这种情况。来自@Ruslan Ostafiychuk,我们可以通过剥离领先的非数字来解决这个问题:

String[] strings = one.replaceFirst("^\\D+","").split("\\D+");

答案 1 :(得分:3)

试试这个:

        Pattern c = Pattern.compile("([0-9][0-9]) | [0-9]");      
        Matcher d = c.matcher(one);
        while(d.find()) {
               System.out.println(d.group());
        }

它将匹配2位数字和1位数字。

<强>结果:

60 
32 
28 
 0
 0
 0

答案 2 :(得分:0)

以下内容:

Pattern a = Pattern.compile("([0-9]{1,2})\\D*([0-9]{1,2})\\D*([0-9]{1,2})");
Matcher b = a.matcher(one);
while (b.find()) {

    String work = b.group(1);
    String work1 = b.group(2);
    String work2 = b.group(3);

    System.out.println("this is work: " + work);
    System.out.println("this is work1: " + work1);
    System.out.println("this is work2: " + work2);

}

输出:

  

这是工作:60

     

这是work1:32

     

这是work2:28

     

这是工作:0

     

这是work1:0

     

这是work2:0

答案 3 :(得分:0)

据我所知,你的字符串包含空格分隔的数字。如果这是正确的,我建议你用空格分割字符串:

String[] strNums = str.split("\\s+");

现在,如果您的原始字符串为60 32 28 Some Characters 0 0 0,则您的数组将包含:603228SomeCharacters,{ {1}},00

现在迭代这个数组并只采用匹配的元素:

0

答案 4 :(得分:0)

只需循环遍历Matcher的matches()方法。此代码打印每个匹配的数字:

import java.util.*;
import java.util.regex.*;

public class Main {
    public static void main(String[] args) {
        String input = "60 32 28 Some Characters 0 0 0";

        Pattern a = Pattern.compile("\\D*(\\d+)");      
        Matcher b = a.matcher(input);
        List<String> nums = new ArrayList<String>();
        while (b.find()) {
               System.out.println("Matched " + b.group(1));
                nums.add(b.group(1));
        }
    }
}
相关问题