0

I have

String input = "one two three four five six seven";

Is there a regex that works with String.split() to grab (up to) two words at a time, such that:

String[] pairs = input.split("some regex");
System.out.println(Arrays.toString(pairs));

results in this:

[one two,two three, three four,four five,five six,six seven]
user2864740
  • 60,010
  • 15
  • 145
  • 220

2 Answers2

5
String[] elements = input.split(" ");
List<String> pairs = new ArrayList<>();
for (int i = 0; i < elements.length - 1; i++) {
    pairs.add(elements[i] + " " + elements[i + 1]);
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
2

No. With String.split(), the things you get out can't overlap.

e.g. you can get: "one two three four" -> {"one","two","three","four"}, but not {"one two","two three", "three four"}

jgon
  • 698
  • 4
  • 11