so_mv
so_mv

Reputation: 3998

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

item1.test,item2.qa,item3.production

from above input line?

Upvotes: 36

Views: 67205

Answers (3)

gnom1gnom
gnom1gnom

Reputation: 752

You should use a positive lookahead and lookbehind:

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

Upvotes: 9

maerics
maerics

Reputation: 156632

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]

Upvotes: 2

Jared
Jared

Reputation: 2474

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));
}

Upvotes: 94

Related Questions