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>。また、実際には 1 回実行regEx.matcher()してから、1 つのマッチャーからグループを引き出す必要があります。書かれているように、正規表現を5回実行し、各グループを1回実行します。find()また、またはを呼び出さない限り、正規表現は実行されません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 に答える