[英]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
您的數組將包含: 60
, 32
, 28
, Some
, Characters
, 0
, 0
, 0
。
現在遍歷此數組並僅采用匹配的元素:
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.