简体   繁体   中英

Java split String in three parts

I need to split String into 3 parts. Example:

String s="a [Title: title] [Content: content]";

Result should be:

s[0]="a"; 
s[1]="Title: title"; 
s[2]="Content: content";

Later I would like to put Title: title and Content: content in a Map as String key-value pair.

You could do something like this,

String s = "a [Title: title] [Content: content]";
String parts[] = s.split("\\]?\\s*\\[|\\]");
System.out.println(Arrays.toString(parts));

OR

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);

Output:

[a, Title: title, Content: content]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM