我有以下案文:
&rule_c(2-7, <<'EOF');
cout << "Hello World.\n";
return x;
EOF我想将这个文本匹配成一个正则表达式。
我在想的是:
^&rule_c\((\d+)\-(\d+),\s?\<\<\s?\'EOF\'\);\r?\n|\r\n?(.*\r?\n|\r\n?)+EOF\r?\n|\r\n?$我用Java试了一下:
private static final String newLine = System.getProperty("line.separator").toString();
...
String textual = "&rule_c(2-7, <<'EOF');" + newLine
+ "cout << "Hello World.\n";" + newLine
+ "return x;" + newLine
+ "EOF" + newLine;
String lineSep = "\\r?\\n|\\r\\n?";
String regex = "^&rule_c\\((\\d+)\\-(\\d+),\\s?\\<\\<\\s?\\'EOF\\'\\);"
+ lineSep + "(.*" + lineSep + ")+EOF" + lineSep + "$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(textual);
if (m.matches()) {
rangeLowerBound = Integer.parseInt(m.group(1));
rangeUpperBound = Integer.parseInt(m.group(2));
String[] tmp = m.group(3).split(lineSep);
System.out.println(tmp.toString());
for (String l : tmp)
System.out.println(l);
lineSet = new ArrayList<String>();
Collections.addAll(lineSet, tmp);
} else
System.out.println("regex doesn't match!");
...我得到的唯一结果是regex doesn't match!。
我在哪里不及格?
发布于 2013-10-10 12:49:35
我使用String lineSep = (?:\\r?\\n|\\r\\n?)+; (而不是实际上匹配|和?字符的String lineSep = [\\r?\\n|\\r\\n?]+; )来解决问题,结合了Pshemo (主要是)和Fedor Skrynnikov的答案和建议。
还使用了波希米亚的建议来删除不必要的字符转义。
这里,gskinner.com's RegEx Tester的例子。
发布于 2013-10-09 15:47:07
| in \\r?\\n|\\r\\n?将整个正则表达式拆分为单独的regex1|regex2部分。为了解决这个问题,你可以把它放在括号里。另外,由于您不想将其包含在组计数中,所以可以使用(?:...)来对非捕获组进行装箱。
所以改变
String lineSep = "\\r?\\n|\\r\\n?";至
String lineSep = "(?:\\r?\\n|\\r\\n?)";顺便说一下,要打印数组的内容,您应该使用Arrays.toString(yourArray)而不是yourArray.toString(),所以可能会更改。
System.out.println(tmp.toString())至
System.out.println(Arrays.toString(tmp))发布于 2013-10-09 15:50:40
我觉得你的问题是在线分离器里。从您的代码示例来看,这对我起了作用。此外,字符串没有正确转义,我不得不从您的示例中转义双引号。
final String newLine = System.getProperty("line.separator").toString();
StringBuilder sb = new StringBuilder();
sb.append("&rule_c(2-7, <<'EOF');");
sb.append(newLine);
sb.append("cout << \"Hello World.\n\";");
sb.append(newLine);
sb.append("return x;");
sb.append(newLine);
sb.append("EOF");
sb.append(newLine);
String textual = sb.toString();
String lineSep = "(\r?\n|\r\n?)";
String regex = "\\&rule_c\\(2\\-7, <<'EOF'\\);"+lineSep+"cout << \"Hello World.\\n\";"+lineSep+"return x;"+lineSep+"EOF"+lineSep;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(textual);
if (m.matches()) {
System.out.println("regex matches!");
}
else {
System.out.println("regex doesn't match!");
}https://stackoverflow.com/questions/19276162
复制相似问题