Nyger
Nyger

Reputation: 215

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?

Upvotes: 2

Views: 233

Answers (2)

Pshemo
Pshemo

Reputation: 124275

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

Upvotes: 10

user177800
user177800

Reputation:

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

Upvotes: 10

Related Questions