Java 对3个或更多单词进行字符串拆分

Java 对3个或更多单词进行字符串拆分,java,regex,Java,Regex,我有一个代码,可以将两个单词分割成一个字符串,然后将它们放入数组中 String words = "chill hit donkey chicken car roast pink rat tree"; 进入 这是我的代码: String[] result = joined.split("(?<!\\G\\S+)\\s"); System.out.printf("%s%n", Arrays.toString(result)); 输出(数组中的4个字): 试图修改正则表达式,但到目

我有一个代码,可以将两个单词分割成一个字符串,然后将它们放入数组中

String words = "chill hit donkey chicken car roast pink rat tree";
进入

这是我的代码:

  String[] result = joined.split("(?<!\\G\\S+)\\s");
  System.out.printf("%s%n", Arrays.toString(result));
输出(数组中的4个字):

试图修改正则表达式,但到目前为止没有任何效果。谢谢。

您可以使用这个正则表达式(使用
re.find()

Java代码

您可以使用这个正则表达式(使用
re.find()

Java代码


只需添加适当数量的“非空白+空白”组合:


joined.split((?只需添加适当数量的“非空白+空白”组合:


joined.split((?用于将文本拆分为N组,我们可以使用

((?:\w+\s){N-1}(?:\w+)其中对于两个项目组,您使用(?:\w+\s){1}(?:\w+)


对于3个项目组,使用((?:\w+\s){2}(?::\w+)等等。

对于将文本拆分为N组,我们可以使用

((?:\w+\s){N-1}(?:\w+)其中对于两个项目组,您使用(?:\w+\s){1}(?:\w+)


对于3个项目组,使用((?:\w+\s){2}(?:\w+)等等。

这里是另一个
find()
version–只需将
{3}
更改为您喜欢的任何数字即可

出去


这里是另一个
find()
version–只需将
{3}
更改为您喜欢的任何数字即可

出去


您应该澄清这是用于
find()
循环,而不是
split()的参数
。您可能希望在回答中注意,OP需要在拆分的Java字符串中转义该正则表达式中的所有反斜杠。@Andreas抱歉..我的internet连接已断..更新..您应该澄清这是用于
find()
循环,而不是
split()的参数
。您可能希望在回答中注意,OP需要在拆分的Java字符串中转义该正则表达式中的所有反斜杠。@Andreas抱歉..我的internet连接丢失..已更新
  String[] result = joined.split("(?<!\\G\\S+)\\s");
  System.out.printf("%s%n", Arrays.toString(result));
 [chill hit donkey, chicken car roast, pink rat tree]
[chill hit donkey chicken, car roast pink rat tree]
((?:\w+\s){2}(?:\w+)) (Replace `2` with `3` for 4 words)
String line = "chill hit donkey chicken car roast pink rat tree";
String pattern = "((?:\\w+\\s){2}(?:\\w+))";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

while (m.find()) {
    System.out.println(m.group(1));
}
// ((?:\w+\W?){3})(?:(\W+|$))
String text = "chill hit donkey chicken car roast pink rat tree";
String regex = "((?:\\w+\\W?){3})(?:(\\W+|$))";
Matcher m = Pattern.compile(regex).matcher(text);
while (m.find()) {
    System.out.println(String.format("'%s'", m.group(1)));
}
'chill hit donkey'
'chicken car roast'
'pink rat tree'