Aug 10, 2021
Java parser string
最近開始研究 Java,順便記錄一下程式寫法,因為一時之間沒有找到比較簡潔的寫法~
目的: 如果 input format 是 xxx1+xxx2+xxx3+…,想要取出數字的部分並且把數字變成一個字串 list
作法:
Parser "test1+test2" to ["1", "2"]private String target = "test";
public List<String> getParseList(String inputStr) {
List<String> resultList = new ArrayList<String>();
if (inputStr != null && inputStr.contains(target)) {
int lastindex = 0;
int beginindex = 0;
while (lastindex != -1) {
lastindex = inputStr.indexOf("+", beginindex);
String num; if (lastindex != -1) {
num = inputStr.substring(beginindex, lastindex);
beginindex = lastindex + 1;
} else {
num = inputStr.substring(beginindex);
} resultList.add(num.replaceAll("[^\\d.]", ""));
}
}
return resultList;
}