鉴于:
String input = "one two three four five six seven";
Run Code Online (Sandbox Code Playgroud)
是否有一个正则表达式,一次String.split()抓取(最多)两个单词,这样:
String[] pairs = input.split("some regex");
System.out.println(Arrays.toString(pairs));
Run Code Online (Sandbox Code Playgroud)
结果如下:
[one two, three four, five six, seven]
Run Code Online (Sandbox Code Playgroud)
这个问题是关于分裂正则表达式.它不是 "找到一种解决方法"或其他"使其以另一种方式工作"的解决方案.
昨晚在这里回答了第一轮.@Reimeus提供的解决方案很棒,并提供以下输出:
My name is the mighty llama
Run Code Online (Sandbox Code Playgroud)
至:
String[] stringArray = string.split("(?<!\\G\\S+)\\s");
My name
is the
mighty llama
Run Code Online (Sandbox Code Playgroud)
但是,我现在发现自己需要纠正我正在做的事情.我实际上需要能够像这样拆分字符串.
My name
name is
is the
the mighty
mighty llama
Run Code Online (Sandbox Code Playgroud)