Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正则表达式在多行上匹配括号中的文本_Java_Regex - Fatal编程技术网

Java 正则表达式在多行上匹配括号中的文本

Java 正则表达式在多行上匹配括号中的文本,java,regex,Java,Regex,我有以下案文: node [ id 2 label "node 2" thisIsASampleAttribute 43 ] node [ id 3 label "node 3" thisIsASampleAttribute 44 ] 我想将每个节点及其内容分组在括号内,例如: node [ id 2 label "node 2" thisIsASampleAttribute 43 ] 但是,我使用以下代码对整个

我有以下案文:

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)*?)


但是,上面的正则表达式效率相对较低。一种可能更好的方法是将非
]
字符与一个否定的字符集匹配,
([^\]]*)


你有足够的斜杠吗?我不是Java方面的专家,但是为什么它在
\n
中只需要一个斜杠,在
\\[
中只需要两个斜杠?似乎仍然在对所有内容进行分组。我已经用包含字符的文本更新了这个问题,如果是这样的话helps@joe我添加了示例..您正在检索第一个捕获组吗?
m.group(1)
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));
}