输入线低于Java正则表达式来提取方括号
Item(s): [item1.test],[item2.qa],[item3.production]
你能不能帮我写的内容中一个Java正则表达式来提取
item1.test,item2.qa,item3.production
从上面输入线
?
输入线低于Java正则表达式来提取方括号
Item(s): [item1.test],[item2.qa],[item3.production]
你能不能帮我写的内容中一个Java正则表达式来提取
item1.test,item2.qa,item3.production
从上面输入线
?
有点更简洁:
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));
}
修整前或后的垃圾后,我会分裂:
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]
你应该用积极的前瞻和回顾后:
(?<=\[)([^\]]+)(?=\])
太棒了,但我怎么能得到相反的结果?我只想保存在方括号内的内容 – candlejack 2017-02-17 18:01:59
我不明白你的问题 - 这正是这个正则表达式所做的。 以输入 '项目(S):[item1.test],[item2.qa],[item3.production]' 它返回 'item1.test' 'item2.qa' 'item3.production' – gnom1gnom 2017-02-28 12:07:02
请记住,这将不支持嵌套的括号。 – Gabe 2010-10-23 21:31:19
如果嵌套或不嵌套,以上解决方案根本无法工作。 – nottinhill 2011-07-10 07:50:06
@Stephan Kristyn:适用于Mac OS X 10.6.7上的Java 1.6。 – maerics 2011-07-11 00:35:53