2

这是我的输入字符串,我想根据下面的正则表达式将它分成 5 个部分,以便我可以打印出 5 个组,但我总是找不到匹配项。我究竟做错了什么 ?

String content="beit Be it enacted by the Senate and House of Representatives of the United States of America in Congress assembled,,<m>Surface Transportation Extension Act of 2012.,<xm>";

Pattern regEx = Pattern.compile("^(.*)(<m>)(.*)(<xm>)(.*)$", Pattern.MULTILINE);
System.out.println(regEx.matcher(content).group(1));
System.out.println(regEx.matcher(content).group(2));
System.out.println(regEx.matcher(content).group(3));
System.out.println(regEx.matcher(content).group(4));
System.out.println(regEx.matcher(content).group(5));
4

2 回答 2

0

您的正则表达式的第 5 次匹配不匹配任何内容 - 之后没有内容<xm>。此外,您应该真正运行regEx.matcher()一次,然后将组从一个匹配器中拉出;如所写,它执行正则表达式 5 次,一次让每个组退出。此外,除非您调用find()或,否则您的 RegEx 永远不会执行matches

于 2013-06-03T19:18:42.290 回答
0
Pattern regEx = Pattern.compile("^(.*)(<m>)(.*)(<xm>)(.*)$", Pattern.MULTILINE);
Matcher matcher = regEx.matcher(content);
if (matcher.find()) { // calling find() is important
// if the regex matches multiple times, use while instead of if
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
    System.out.println(matcher.group(3));
    System.out.println(matcher.group(4));
    System.out.println(matcher.group(5));
} else {
    System.out.println("Regex didn't match");
}
于 2013-06-03T19:18:49.883 回答