Java regex split text (both the delimiter and the order may be unknown) -
i'm trying split text "name:jack,berk,john;teacher:smith,jan;course:math;"
, hope result contains 3 sub-strings (or less, depends on appearance of 'name' 'teacher' 'course'), is:
"name:jack,berk,john;"
"teacher:smith,jan;"
"course:math;"
but appearance order of identifiers 'teacher,name,course'
not fixed, can 'course ,name, teacher'
, can lack 1 or two, has 'name' identifiers.
also delimiter between identifiers not fixed, in example ';'
,but can '、\\s,'
.
i have tried many times 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 appreciated.
edit: regex without looking specific delimiter.
rather splitting string match on regex:
(name|teacher|course):(.+?)(?=\w*(?:name|teacher|course|$))
working demo
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]); }
Comments
Post a Comment