我需要将String拆分为3个部分。 例如:
String s="a [Title: title] [Content: content]";
结果应该是:
s[0]="a";
s[1]="Title: title";
s[2]="Content: content";
稍后我想将Title:title和Content:content作为字符串键值对放在Map中。
答案 0 :(得分:0)
你可以这样做,
String s = "a [Title: title] [Content: content]";
String parts[] = s.split("\\]?\\s*\\[|\\]");
System.out.println(Arrays.toString(parts));
或强>
String s = "a [Title: title] [Content: content]";
String parts[] = s.split("\\s(?![^\\[\\]]*\\])"); # Splits the input according to spaces which are not present inside the square brackets
ArrayList<String> l = new ArrayList<String>();
for (String i: parts) # iterate over the array list elements.
{
l.add(i.replaceAll("[\\[\\]]", "")); # replace all [, ] chars from the list elements and append it to the declared list l
}
System.out.println(l);
输出:
[a, Title: title, Content: content]