Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into overlapping parts

I have String like this:

String s = "1234567890";

I'd like use split("regex") to get this output:

12
23
34
45
56
67
78
89
90

What regex should I use?

like image 950
Nyger Avatar asked Nov 30 '25 11:11

Nyger


2 Answers

This is not an appropriate problem to solve with a regular expression

When there is a much easier and simpler way to solve the problem and most importantly more obvious and self documenting way to do it.

public static void main(final String[] args)
{
    final String s = "1234567890";
    for (int i = 0; i < s.length() - 1; i++)
    {
        System.out.println(s.substring(i,i+2));
    }
}

12
23
34
45
56
67
78
89
90

Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems. -- Jamie Zawinski

I agree with Jarrods answer, if you don't have to use regex and there are other easy solutions then try to avoid regex. But in case you have to use it read rest of my answer...

Unfortunately you wont be able to do it with split, because you want to use same digit in few split parts which is impossible, because split cant add new content to data.

You can do it with look-ahead mechanism

String data = "1234567890";
Matcher m = Pattern.compile("(?=(\\d\\d))").matcher(data);
while (m.find())
    System.out.println(m.group(1));

output:

12
23
34
45
56
67
78
89
90
like image 43
Pshemo Avatar answered Dec 03 '25 01:12

Pshemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!