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

誰が私が正しくなかったことを伝えることができますか?

Javascript で正規表現をテストしたところ、うまくいきました。ここを参照してください。

4

2 に答える 2

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 < 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));
        }
    }
于 2013-01-27T04:24:49.817 に答える
0

これを試して:

Pattern p = Pattern.compile("(program|function|process).*?(\\{.*?\\})\\s*", Pattern.DOTALL);
Matcher m = p.matcher(input);
while(m.find()) {
      System.out.println(m.group(2));
}
于 2013-01-27T04:25:03.803 に答える