Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regular expression to extract content within square brackets

Tags:

java

regex

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?

like image 900
so_mv Avatar asked Oct 23 '10 21:10

so_mv


People also ask

How do you escape a square bracket in regex Java?

You can use the \Q and \E special characters... anything between \Q and \E is automatically escaped. In Java string literal format it would be "\\Q[0-9]\\E" or "\\Q" + regex + "\\E".

How do you match square brackets in regex?

You can omit the first backslash. [[\]] will match either bracket. In some regex dialects (e.g. grep) you can omit the backslash before the ] if you place it immediately after the [ (because an empty character class would never be useful): [][] .


2 Answers

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)); } 
like image 75
Jared Avatar answered Sep 23 '22 16:09

Jared


You should use a positive lookahead and lookbehind:

(?<=\[)([^\]]+)(?=\]) 
  • (?<=[) Matches everything followed by [
  • ([^]]+) Matches any string not containing ]
  • (?=]) Matches everything before ]
like image 22
gnom1gnom Avatar answered Sep 20 '22 16:09

gnom1gnom