Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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,我想提取A,B,C后面的大括号中的内容。我编写了下面的代码,但它不起作用 program A { int x = 10; tuple date { int day; int month; int year; } } function B { int y = 20; ... } process C { more code; } 有人能告诉我什么地方不对吗 我已经在Javascri

我想提取A,B,C后面的大括号中的内容。我编写了下面的代码,但它不起作用

program A {
   int x = 10;
   tuple date {
            int day;
            int month;
            int year;
   }
}

function B {
    int y = 20;
    ...
}

process C {
    more code;
}
有人能告诉我什么地方不对吗

我已经在Javascript中测试了正则表达式,它成功了。请参阅。

试试看

public class Test {
    public static void main(String[] args) throws IOException {
        String input = FileUtils.readFileToString(new File("input.txt"));
        System.out.println(input);
        Pattern p = Pattern.compile("(program|function|process).*?\\{(.*?)\\}\n+(program|function|process)", Pattern.DOTALL);
        Matcher m = p.matcher(input);
        while(m.find()) {
            System.out.println(m.group(1));
        }
    }
}
输出

    Pattern p = Pattern.compile("\\{(.*?)\\}(?!\\s*\\})\\s*", Pattern.DOTALL);
    Matcher m = p.matcher(input);
    while (m.find()) {
        System.out.println(m.group(1));
    }
不过我认为这会更可靠

   int x = 10;
   tuple date {
            int day;
            int month;
            int year;
   }


    int y = 20;
    ...


    more code;
for(int i=0,j=0,n=0;i
试试这个:

    for (int i = 0, j = 0, n = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (c == '{') {
            if (++n == 1) {
                j = i;
            }
        } else if (c == '}' && --n == 0) {
            System.out.println(input.substring(j + 1, i));
        }
    }

正则表达式不能处理任意嵌套的分隔符。要做到这一点,您需要一个真正的状态机解析器。如果您仔细查看Rubular示例中的输出,它似乎不符合您声明的要求。@JimGarrison我知道。我只想处理这个特定的情况(即,使它在给定的输入上工作)。我正在处理其他人的问题,并且已经用Javascript实现了。我很难让它在Java中工作。你能建议我如何改进我的帖子吗?不,这不是真正的问题。问题是它不能提取我想要的东西。它从第一个大括号匹配到最后一个大括号。由于存在嵌套大括号,因此需要查找,请参见@Terry Li\}(?!\\s*\})意思是}后面不跟\s*}
Pattern p = Pattern.compile("(program|function|process).*?(\\{.*?\\})\\s*", Pattern.DOTALL);
Matcher m = p.matcher(input);
while(m.find()) {
      System.out.println(m.group(2));
}