开发者

java regular expression to extract content within square brackets

input line is below

Item(s): [item1.test],[item2.qa],[item3.production]

Can you help me write a Java regular expression to extract

ite开发者_高级运维m1.test,item2.qa,item3.production

from above input line?


A bit more concise:

String in = "Item(s): [item1.test],[item2.qa],[item3.production]";

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(in);

while(m.find()) {
    System.out.println(m.group(1));
}


You should use a positive lookahead and lookbehind:

(?<=\[)([^\]]+)(?=\])
  • (?<=[) Matches everything followed by [
  • ([^]]+) Matches any string not containing ]
  • (?=]) Matches everything before ]


I would split after trimming preceding or trailing junk:

String s = "Item(s): [item1.test], [item2.qa],[item3.production] ";
String r1 = "(^.*?\\[|\\]\\s*$)", r2 = "\\]\\s*,\\s*\\[";
String[] ss = s.replaceAll(r1,"").split(r2);
System.out.println(Arrays.asList(ss));
// [item1.test, item2.qa, item3.production]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜