繁体   English   中英

用正则表达式捕获数字

[英]Capturing numbers with 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);



}

}

但是,我无法捕获每个数字。 我看过其他教程,但是我找不到正则表达式在做什么,或者除了使用正则表达式之外还有其他解决方案。 我不使用子字符串,因为数字之间的文本长度通常会有所不同。 任何帮助,将不胜感激。

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

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

这也可行,但是我通常会忘记那些表示“ not”的内置字符类(感谢@Pshemo):

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

一个警告: Strings的第一个元素可能是一个空字符串。 如果第一个字符不是数字,则会发生这种情况。 从@Ruslan Ostafiychuk,这里是我们可以通过去除开头的非数字来解决的方法:

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

尝试这个:

        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

输入以下内容:

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

这是工作1:32

这是工作2:28

这是工作:0

这是工作1:0

这是工作2:0

据我了解,您有包含空格分隔数字的字符串。 如果这是正确的,我建议您按空格分割字符串:

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

现在,如果您的原始字符串是60 32 28 Some Characters 0 0 0您的数组将包含: 603228SomeCharacters000

现在遍历此数组并仅采用匹配的元素:

List<Integer> numbers = new ArrayList<>();
for (String s : strNums) {
   try {
        numbers.add(Integer.parseInt(s));
   } catch (NumberFormatException e) {
        // ignore
   }
}

只需遍历Matcher的matchs()方法即可。 此代码显示每个匹配的数字:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM