java正则表达式提取方括号内的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4006113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:14:41 来源:igfitidea点击:
java regular expression to extract content within square brackets
提问by so_mv
input line is below
输入线在下面
Item(s): [item1.test],[item2.qa],[item3.production]
Can you help me write a Java regular expression to extract
你能帮我写一个Java正则表达式来提取吗
item1.test,item2.qa,item3.production
from above input line?
从上面的输入行?
采纳答案by Jared
A bit more concise:
更简洁一点:
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));
}
回答by maerics
I would split after trimming preceding or trailing junk:
我会在修剪前面或后面的垃圾后拆分:
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]
回答by gnom1gnom
You should use a positive lookahead and lookbehind:
您应该使用积极的前瞻和后视:
(?<=\[)([^\]]+)(?=\])
- (?<=[) Matches everything followed by [
- ([^]]+) Matches any string not containing ]
- (?=]) Matches everything before ]
- (?<=[) 匹配所有后跟 [
- ([^]]+) 匹配任何不包含 ] 的字符串
- (?=]) 匹配 ] 之前的所有内容