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]