[英]Java - Extracting text from string by a common length and prefix
我有一個文本字符串“ 9926 9928 9951 9953 0 30 57 12 40 54 30”
我對以99開頭的4位數字感興趣。其他數字是多余的。
所需輸出:
9926
9928
9951
9953
我的代碼:
String str = " 9926 9928 9951 9953 0 30 57 12 40 54 30";
Iterable<String> result = Splitter.onPattern("99").fixedLength(4).split(str);
實際輸出:
992
6 99
28 9
951
9953
0 3
0 57
12
40 5
4 30
將Matcher
與正則表達式99\\d{2}
:
String str = " 9926 9928 9951 9953 0 30 57 12 40 54 30";
Matcher m = Pattern.compile("99\\d{2}").matcher(str);
while (m.find())
System.out.println(m.group());
9926 9928 9951 9953
另請參閱: Pattern
請注意,在正則表達式\\d
是一個預定義的字符類,它等效於[0-9]
。 此外, {2}
是一個量詞 ,表示“無論在哪個位置,兩次”。 因此, 99\\d{2}
匹配兩個9
后跟兩個任意數字:
如果要使用許多不同的字符串執行此操作,請考慮預編譯正則表達式並將Pattern
實例存儲在某個static final
變量中,並在需要執行此操作時使用它。
您可以使用以下算法來做自己的事情。
whitespace
字符。 startsWith()
方法,這是您需要的數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.