Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split at every i-th and j-th char

Tags:

java

regex

split

I need to split a string at every i-th and j-th character, where i and j can change according to input parameters. If for example i have an input

String s = "1234567890abcdef";
int i = 2;
int j = 3;

I want my output to be an array of:

[12, 345, 67, 890, ab, cde, f]

I found a compact regex to split at every n-th char. Example for n = 3 using "(?<=\\G...)" or "(?<=\\G.{3})"

String s = "1234567890abcdef";
int n = 3;
System.out.println(Arrays.toString(s.split("(?<=\\G.{"+n+"})")));

//output: [123, 456, 789, 0ab, cde, f]

How to modify the above regex to split at every 2nd and 3rd char alternately?

A naive chaining like "(?<=\\G.{2})(?<=\\G.{3})" did not work.

like image 885
wannaBeDev Avatar asked Dec 18 '22 11:12

wannaBeDev


1 Answers

I don't think you can do this with split(), because every match should be aware of the pattern previously matched.

If you don't want to manually iterate over the string's characters, you can use something like this:

Matcher m = Pattern.compile("(.{0,2})(.{0,3})").matcher("1234567890abcdef");
List<String> list = new ArrayList<>();
while (m.find()) {
  for (int i = 1; i <= 2; i++) {
    if (!m.group(i).isEmpty()) {
      list.add(m.group(i));
    }
  }
}
System.out.println(list);  // prints [12, 345, 67, 890, ab, cde, f]
like image 195
horcrux Avatar answered Dec 31 '22 05:12

horcrux