从字符串中提取多个子字符串(例如"B #####",其中#是所有可能的数字) - Java - Android

Mat*_*ias 0 java android substring

我想提取所有可能的子串B ##### M ##### CB ##### CM ##### LB ##### LM #####(其中#是数字)来自一个字符串.每个字符串可以包含一个或多个这些可能的子字符串.

字符串("LB03452 - 测试,文件名B12345,test2 - 第二个文件的名称")的结果应该是字符串列表{LB03452,B12345}.

Ben*_* P. 5

您可以使用PatternMatcher类来解决此问题.这是一个很小的例子,您可以根据需要进行调整:

String input = "LB03452 - Test, name of the file B12345, test2 - name of second file";
List<String> output = new ArrayList<>();
Pattern p = Pattern.compile("(B|M|CB|CM|LB|LM)[0-9]+");
Matcher m = p.matcher(input);

while (m.find()) {
    output.add(m.group());
}
Run Code Online (Sandbox Code Playgroud)

如果我打印输出

System.out.println(output);
Run Code Online (Sandbox Code Playgroud)

我明白了:

[LB03452, B12345]
Run Code Online (Sandbox Code Playgroud)