2010-10-23 79 views
23

输入线低于Java正则表达式来提取方括号

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

你能不能帮我写的内容中一个Java正则表达式来提取

item1.test,item2.qa,item3.production 
从上面输入线

回答

68

有点更简洁:

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

修整前或后的垃圾后,我会分裂:

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

请记住,这将不支持嵌套的括号。 – Gabe 2010-10-23 21:31:19

+0

如果嵌套或​​不嵌套,以上解决方案根本无法工作。 – nottinhill 2011-07-10 07:50:06

+0

@Stephan Kristyn:适用于Mac OS X 10.6.7上的Java 1.6。 – maerics 2011-07-11 00:35:53

5

你应该用积极的前瞻和回顾后:

(?<=\[)([^\]]+)(?=\]) 
  • (?< = [)匹配everythi NG,然后按[
  • ([^] +)匹配不包含任何字符串]
  • (?=])匹配之前的一切]
+0

太棒了,但我怎么能得到相反的结果?我只想保存在方括号内的内容 – candlejack 2017-02-17 18:01:59

+0

我不明白你的问题 - 这正是这个正则表达式所做的。 以输入 '项目(S):[item1.test],[item2.qa],[item3.production]' 它返回 'item1.test' 'item2.qa' 'item3.production' – gnom1gnom 2017-02-28 12:07:02