輸入線低於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