Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

java - Split regex to extract Strings of contiguous characters

Is there a regex that would work with String.split() to break a String into contiguous characters - ie split where the next character is different to the previous character?

Here's the test case:

String regex = "your answer here";
String[] parts = "aaabbcddeee".split(regex);
System.out.println(Arrays.toString(parts));

Expected output:

[aaa, bb, c, dd, eee]

Although the test case has letters only as input, this is for clarity only; input characters may be any character.


Please do not provide "work-arounds" involving loops or other techniques.

The question is to find the right regex for the code as shown above - ie only using split() and no other methods calls. It is not a question about finding code that will "do the job".

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is totally possible to write the regex for splitting in one step:

"(?<=(.))(?!\1)"

Since you want to split between every group of same characters, we just need to look for the boundary between 2 groups. I achieve this by using a positive look-behind just to grab the previous character, and use a negative look-ahead and back-reference to check that the next character is not the same character.

As you can see, the regex is zero-width (only 2 look around assertions). No character is consumed by the regex.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...