【发布时间】:2014-06-17 19:25:14
【问题描述】:
我有这些包含数字集的字符串。我需要做的是捕获每一组数字并为它们创建新的字符串。例如,在字符串:“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);
}
}
但是,我无法捕获每个数字。我查看了其他教程,但我找不到我的正则表达式做错了什么,或者除了使用正则表达式之外是否还有其他解决方案。我一直远离使用子字符串,因为数字之间的文本通常长度不同。任何帮助将不胜感激。
【问题讨论】:
-
您也许可以一次捕获一个数字,循环并将每个数字添加到一个数组中,然后使用该数组获取所需数字的变量。
-
您是否尝试使用 3 个匹配组捕获 6 个单独的字符串?
-
@Jerry,我会将每个都放入一个数组中,但字符串本身已经在一个数组中,需要匹配单独数组中的项目。我希望远离另一个阵列哈。
-
@MxyL,对不起,我尝试使用更多匹配组,但遇到了 indexoutofboundsexception 错误