[英]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;
}
I'd like to extract whatever is inside the curly braces following A, B, C. I write the following code, but it does not work. 我想提取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));
}
}
}
Anyone could tell what I didn't get right? 有人能告诉我我做错了什么吗?
I've tested the regular expression in Javascript and it worked. 我已经测试了Java中的正则表达式,并且可以正常工作。 See here . 看这里 。
try 尝试
Pattern p = Pattern.compile("\\{(.*?)\\}(?!\\s*\\})\\s*", Pattern.DOTALL);
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.group(1));
}
output 输出
int x = 10;
tuple date {
int day;
int month;
int year;
}
int y = 20;
...
more code;
still I think this would be more reliable 我仍然认为这会更可靠
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));
}
}
try this: 尝试这个:
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.