要將多個方括弧[...]包起的字串分割並取出的做法如下。
使用正則表示式regex來取得每個括號中的值。
String s1 = "[1][1,2,3][1,2,3,4,5]";
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher match = pattern.matcher(s1);
List ss1 = new ArrayList<>();
while (match.find()) {
ss1.add(match.group(1));
}
for (String s : ss1) {
System.out.println(s);
}
System.out.println("===========================");
String s2 = "[1],[1,2,3],[1,2,3,4,5]";
match = pattern.matcher(s2);
List ss2 = new ArrayList<>();
while (match.find()) {
ss2.add(match.group(1));
}
for (String s : ss2) {
System.out.println(s);
}
印出結果如下
1
1,2,3
1,2,3,4,5
===========================
1
1,2,3
1,2,3,4,5
方括號(square brackets)[]在正則表示式中有特殊意義,所以實字用跳脫符號\\[來表示。
點(period).符號代表任意字元。
星號(asterisk)*表示前面的字符可以出現0次或多次,因為前面是\\[.,所以代表左方括弧後接任意符號可以出現0次或多次
問號(question mark)?表示前面的字符可以出現0次或1次,因為前面是\\[.*,後面是\\],所以代表左方括弧後接任意符號可以出現0次或1次,而且後面必須緊接著]。
參考:
沒有留言:
張貼留言