java - Why does String.split() return extra elements here? -
i trying split string using regexp returns element in array. please help. following program:
public class test { public static void main(string[] arg){ string str1 = "{abc}{def}"; string delim = "[{}]+"; string[] tokens = str1.split(delim); (int = 0; < tokens.length; i++) { system.out.println("token value: "+ tokens[i]); } } }
output:
token value: token value: abc token value: def
why first token empty string? how can fixed?
the reason have empty initial element target string starts delimiter. splitting ",1,2"
on ,
result in 3 entries, first being blank, same result. (you don't blank @ end because string#split
explicitly removes them unless give negative second argument.)
if know string start delimiter , it's 1 character, remove it:
string[] tokens = str1.substring(1).split(delim);
edit: or general case, see bohemian's answer removes first matching delim regardless of length.
otherwise, can loop:
import java.util.regex.*; public class splittest { public static void main(string[] arg){ string str1 = "{abc}{def}"; matcher m = pattern.compile("\\{([^}]+)\\}").matcher(str1); while (m.find()) { system.out.println("token value: " + m.group(1)); } } }
here's breakdown of pattern string:
- the
\\{
@ beginning matches literal{
- the
(
, corresponding)
later create capture group - within capture group,
[^}]+
means "one or more of character isn't}
- the trailing
\\}
match literal}
then loop through matches in string, getting value of capture group
Comments
Post a Comment