【发布时间】:2023-04-05 11:14:01
【问题描述】:
输入线在下方
Item(s): [item1.test],[item2.qa],[item3.production]
你能帮我写一个Java正则表达式来提取吗
item1.test,item2.qa,item3.production
从上面的输入行?
【问题讨论】:
输入线在下方
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));
}
【讨论】:
您应该使用积极的前瞻和后视:
(?<=\[)([^\]]+)(?=\])
【讨论】:
Item(s): [item1.test],[item2.qa],[item3.production] 它返回 item1.test item2.qa item3.production
我会在修剪前面或后面的垃圾后拆分:
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]
【讨论】: