Java正则表达式匹配大括号之间的文本

标签 java regex

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

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

process C {
    more code;
}

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

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));
        }
    }
}

有人能看出我哪里做错了吗?

我已经在 J​​avascript 中测试了正则表达式并且它有效。请参阅here .

最佳答案

尝试

    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 < 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));
        }
    }

关于Java正则表达式匹配大括号之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14544199/

相关文章:

java - 如果输入了选项之外的内容,如何重复 if 或 switch 语句?

java - 使用 spring 数据存储库而不是生成的轴突存储库

mysql - SQL-Server-2008 中的正则表达式

php - 正则表达式模式 'pL' 有什么作用?

java - Spring MVC 将值放入 XML 配置文件

java - ANTLR Ubuntu Java Makefile

java - 如何在 JFrame 中创建视口(viewport)?

regex - 字符串插值的奇怪错误

c - 正则表达式教程或书籍

java - 使用正则表达式解析街道地址