我试图在java中找到一个正则表达式,它将在句子中提取成对的连续单词,如下例所示。
输入:word1 word2 word3 word4 ....
输出:
- 单词1 单词2
- 字2字3
- 字3字4
ETC..
知道该怎么做吗?
Matcher m = Pattern.compile("(?:^|(?<=\\s))(?=(\\S+\\s+\\S+)(?=\\s|$))")
.matcher("word1 word2 word3 word4");
while (m.find()) {
System.out.println(m.group(1));
}
word1 word2
word2 word3
word3 word4
在此处测试此代码。
这个给你:
public class Example {
public static void main(String[] args) {
String words = "word1 word2 word3 word4";
String regex="\\w+\\s+\\w+";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(words);
while(matcher.find()){
String found = matcher.group();
System.out.println(found);
String splitted = found.split("\\s+")[1];
words = words.replace(found, splitted);
matcher = p.matcher(words);
}
}
}
也提供一个没有不合理复杂性的解决方案......
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+"
一个或多个单词,然后是一个或多个空格,然后是一个或多个单词。
更新 : -
刚刚注意到上面的正则表达式错过了你的第二行输出。因此,您可以将字符串拆分为space
,然后使用您的数组。
String[] words = str.split("\\s+");
然后为每对索引获取消息。