Java 将字符串分成三部分
Java split String in three parts
我需要将字符串拆分为 3 个部分。
示例:
String s="a [Title: title] [Content: content]";
结果应该是:
s[0]="a";
s[1]="Title: title";
s[2]="Content: content";
稍后我想将 Title: title 和 Content: content 作为字符串键值对放在 Map 中。
你可以这样做,
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]
我需要将字符串拆分为 3 个部分。 示例:
String s="a [Title: title] [Content: content]";
结果应该是:
s[0]="a";
s[1]="Title: title";
s[2]="Content: content";
稍后我想将 Title: title 和 Content: content 作为字符串键值对放在 Map 中。
你可以这样做,
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]