正则表达式将字符串拆分为5个部分,如下所示

时间:2013-06-03 19:15:10

标签: java regex

这是我的输入字符串,我想根据下面的正则表达式将其分解为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));

2 个答案:

答案 0 :(得分:0)

你的正则表达式的第5场比赛与任何事情都不匹配 - <xm>之后没有内容。另外,你应该真正运行regEx.matcher()一次,然后将这些组从一个匹配器中拉出来;如上所述,它执行正则表达式5次,一次以使每个组退出。除非您致电find()matches,否则您的RegEx永远不会被执行。

答案 1 :(得分: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");
}