regex - Java pattern to delimit string and find field -


i once again need cannot figure out how regex going.

heres string want split:

string str = "err||||test|get|post|update|" 

i have function given field index starting 1 return string @ position after splitting string. problem regex not return empty strings between delimiters counted towards field index. how can modify regex include these empty fields ?

private static string extractfield(string strt, int fieldno) {     pattern pattern = pattern.compile("[^|]+");     string str = strt.replaceall("\\r", "");     matcher matcher = pattern.matcher(str);     int = 1;     while (matcher.find()) {         string fs = matcher.group().trim();         system.out.println("result: \"" + fs + "\"");         if (i++==fieldno) {             return fs;         }     }     return ""; } 

as looking pattern-based solution, can use regex:

(?<=(^|\|))(.*?)(?=(\||$)) 

those positive lookahead ((?=x)) , positive look-behind ((?<=x)). mill match between 2 |s, or between start of string (^) , |, or between | , end of string ($). lookaheads , look-behinds zero-width assertions, not include | in groups. also, ? in .*? makes non-greedy.

code:

private static string extractfield(string strt, int fieldno) {     pattern pattern = pattern.compile("(?<=(^|\\|))(.*?)(?=(\\||$))");     string str = strt.replaceall("\\r", "");     matcher matcher = pattern.matcher(str);     int = 1;     while (matcher.find()) {         string fs = matcher.group().trim();         system.out.println("result: \"" + fs + "\"");         if (i++==fieldno) {             return fs;         }     }     return ""; } 

results "err||||test|get|post|update|":

result: "err" result: "" result: "" result: "" result: "test" result: "get" result: "post" result: "update" result: "" 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -