Reputation: 113
I'm trying to split a text like "name:jack,berk,john;teacher:smith,jan;course:math;"
And I hope the result contains 3 sub-strings (or less, depends on the appearance of 'name' 'teacher' 'course'), which is:
"name:jack,berk,john;"
"teacher:smith,jan;"
"course:math;"
But the appearance order of identifiers 'teacher,name,course'
is not fixed, it can be 'course ,name, teacher'
and it also can lack one or two, just like only has 'name' identifiers.
Also the delimiter between identifiers is not fixed, in the example is ';'
,but also can be '、\\s,'
.
I have tried many times but it not works.
String str = "name:jack,berk,john;teacher:smith,jan;course:math;
str = str.replaceAll("(.*)(.)(name|teacher|course)(.*)(.)(name|teacher|course)(.*)", "$1--$3$4--$6$7");
System.out.println(str);
Any suggestions would be appreciated.
Upvotes: 3
Views: 297
Reputation: 784958
EDIT: Regex without looking for a specific delimiter.
Rather than splitting the string do a match on this regex:
(name|teacher|course):(.+?)(?=\W*(?:name|teacher|course|$))
Code:
Pattern p = Pattern.compile("(name|teacher|course):(.+?)(?=\\W*(?:name|teacher|course|$))");
Matcher m = p.matcher(name:jack,berk,john;teacher:smith,jan;course:math;);
while (m.find()) {
System.out.println(m.group(1) + " :: " + m.group[2]);
}
Upvotes: 4
Reputation:
You can replace all the delimiters with an unique delimiter and then use String.split
.
String input = "name:jack,berk,john;teacher:smith,jan-course:math;";
String uniqueDelimiter = ";";
String[] otherDelimiters = new String[2];
otherDelimiters[0] = "\\s";
otherDelimiters[1] = "-";
for (String delimiter : otherDelimiters) {
input = input.replaceAll(delimiter, uniqueDelimiter);
}
String[] keyList = input.split(uniqueDelimiter);
Upvotes: 0
Reputation: 36304
public static void main(String[] args) {
String str = "name:jack,berk,john;teacher:smith,jan;course:math;";
String[] values = str.split(";");
for (String s : values) {
if (s.contains("name:")) {
System.out.println("name : " + s.replaceAll("name:", ""));
} else if (s.contains("teacher:")) {
System.out.println("teacher : " + s.replaceAll("teacher:", ""));
} else if (s.contains("course:")) {
System.out.println("course : " + s.replaceAll("course:", ""));
}
}
}
O/P :
name : jack,berk,john
teacher : smith,jan
course : math
Upvotes: 1