以下の例のように、文章内の連続した単語のペアを抽出する正規表現を Java で見つけようとしています。
入力: word1 word2 word3 word4 ....
出力:
- 単語1 単語2
- 単語2 単語3
- 単語3 単語4
等..
それを行う方法はありますか?
不当な複雑さのないソリューションを提供しすぎる...
final String in = "word1 word2 word3 word4";
final String[] words = in.split("\\s+");
for (int i = 0; i < words.length - 1; i++)
System.out.println(words[i] + " " + words[i+1]);
版画
word1 word2
word2 word3
word3 word4
どうぞ: -
"\\w+\\s+\\w+"
1 つ以上の単語、1 つ以上のスペース、1 つ以上の単語。
アップデート : -
上記の正規表現では、出力の 2 行目が欠落していることに気付きました。したがって、文字列を で分割space
して、配列を操作できます。
String[] words = str.split("\\s+");
そして、インデックスのすべてのペアの単語を取得します。