14

javaで正規表現パターンの先読み部分を出力する方法はありますか?

    String test = "hello world this is example";
    Pattern p = Pattern.compile("\\w+\\s(?=\\w+)");
    Matcher m = p.matcher(test);
    while(m.find())
        System.out.println(m.group());

このスニペットは出力します:

こんにちは
世界
これ
です

私がやりたいのは、単語をペアとして出力することです:

Hello world
world これ

例です

どうやってやるの?

4

1 に答える 1

15

先読み式の中にキャプチャ括弧を入れるだけです:

String test = "hello world this is example";
Pattern p = Pattern.compile("\\w+\\s(?=(\\w+))");
Matcher m = p.matcher(test);
while(m.find()) 
    System.out.println(m.group() + m.group(1));
于 2011-04-02T14:17:08.110 に答える