[英]Java regex matching text between curly brace
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));
}
}
}
有人能告訴我我做錯了什么嗎?
我已經測試了Java中的正則表達式,並且可以正常工作。 看這里 。
嘗試
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));
}
}
嘗試這個:
Pattern p = Pattern.compile("(program|function|process).*?(\\{.*?\\})\\s*", Pattern.DOTALL);
Matcher m = p.matcher(input);
while(m.find()) {
System.out.println(m.group(2));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.