Java - Extract text from a string with a common length and prefix

I have a text string "9926 9928 9951 9953 0 30 57 12 40 54 30"

I'm interested in 4-digit digits with the prefix 99. Other numbers are redundant.

Output Required:

9926
9928
9951
9953

My code is:

String str = " 9926 9928 9951 9953 0 30 57 12 40 54 30";
Iterable<String> result = Splitter.onPattern("99").fixedLength(4).split(str);

Actual output:

992
6 99
28 9
951 
9953
 0 3
0 57
 12 
40 5
4 30
+4
source share
2 answers

Use Matcherwith regex 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

See also: Pattern

, \d , [0-9]. , {2} , ", , ". , 99\d{2} 9, :

Regular expression visualization

Debuggex

, Pattern static final, , .

+4

, .

+1

All Articles