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?
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".
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): [][] .
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:
(?<=\[)([^\]]+)(?=\])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With