我有一个文本字符串“9926 9928 9951 9953 0 30 57 12 40 54 30”
我感兴趣的是 4 位数字,前缀为 99。其他数字是多余的。
期望的输出:
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
是一个 predefined character class相当于[0-9]
。此外,{2}
是一个 quantifier这意味着“无论之前,两次”。因此,99\d{2}
匹配两个 9
后跟两个任意数字:
如果您要对许多不同的字符串执行此操作,请考虑预编译正则表达式并将 Pattern
实例存储在某个 static final
变量中,使用每当您想进行操作时。
关于Java - 按通用长度和前缀从字符串中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19409336/