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

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

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


至尊宝的传说
浏览 105回答 2
2回答

海绵宝宝撒

最后用了下面这个不雅的版本,因为入口字符串来自Text Recognition,包含一些识别错误。所述方法有时提供更好的结果。公共列表extract_file_references(字符串字符串){&nbsp; &nbsp; List<String> output = new ArrayList<>();&nbsp; &nbsp; for(int i=0; i<string.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; if ((Character.toString(string.charAt(i)).equals("B") || Character.toString(string.charAt(i)).equals("M")) && Character.isDigit(string.charAt(i+1)) && Character.isDigit(string.charAt(i+2)) && Character.isDigit(string.charAt(i+3)) && Character.isDigit(string.charAt(i+4)) && Character.isDigit(string.charAt(i+5)) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.add(string.substring(i, i+6));&nbsp; &nbsp; &nbsp; &nbsp; } else if (Character.toString(string.charAt(i)).equals("C") && ((Character.toString(string.charAt(i+1)).equals("B"))||Character.toString(string.charAt(i+1)).equals("M")) && Character.isDigit(string.charAt(i+2)) && Character.isDigit(string.charAt(i+3)) && Character.isDigit(string.charAt(i+4)) && Character.isDigit(string.charAt(i+5)) && Character.isDigit(string.charAt(i+6)) ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.add(string.substring(i, i+7));&nbsp; &nbsp; &nbsp; &nbsp; } else if (Character.toString(string.charAt(i)).equals("L") && ((Character.toString(string.charAt(i+1)).equals("B"))||Character.toString(string.charAt(i+1)).equals("M")) && Character.isDigit(string.charAt(i+2)) && Character.isDigit(string.charAt(i+3)) && Character.isDigit(string.charAt(i+4)) && Character.isDigit(string.charAt(i+5)) && Character.isDigit(string.charAt(i+6))) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output.add(string.substring(i, i+7));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }//fin du for&nbsp; &nbsp; return output;&nbsp; &nbsp; }// fin de extract_file_reference
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java