我有以下文字:
node [
id 2
label "node 2"
thisIsASampleAttribute 43
]
node [
id 3
label "node 3"
thisIsASampleAttribute 44
]
我想将每个节点及其内容分组在方括号内,例如:
node [
id 2
label "node 2"
thisIsASampleAttribute 43
]
但是,我用下面的代码将整个文本分组:
Pattern p = Pattern.compile("node \\[\n(.*|\n)*?\\]", Pattern.MULTILINE);
Matcher m = p.matcher(text);
while(m.find())
{
System.out.println(m.group());
}
编辑文字:
node [\n" +
" id 2\n" +
" label \"node 2\"\n" +
" thisIsASampleAttribute 43\n" +
" ]\n" +
" node [\n" +
" id 3\n" +
" label \"node 3\"\n" +
" thisIsASampleAttribute 44\n" +
" ]\n"
问题是您只捕获了最后一个字符(.*|\n)*?
(因为.?
它不在捕获组中)。
您可以将捕获组更改为非捕获组,然后将其*?
与捕获组一起包装,以捕获所有匹配项((?:.*?|\n)*?)
。
Pattern p = Pattern.compile("node \\[\\n((?:.*?|\\n)*?)\\]", Pattern.MULTILINE);
Matcher m = p.matcher(text);
while(m.find())
{
System.out.println(m.group(1));
}
但是,上述正则表达式效率相对较低。可能更好的方法是将非]
字符与否定的字符集匹配([^\]]*)
。
Pattern p = Pattern.compile("node \\[\\n([^\\]]*)\\]", Pattern.MULTILINE);
Matcher m = p.matcher(text);
while(m.find())
{
System.out.println(m.group(1));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句