I want to take any given string and split it based on repeating characters.
我想取任意给定的字符串,并基于重复的字符对其进行分割。
As an example, if I were to input the string abcaaabbc
, I would want to output an array of strings equal to: [abca, a, ab, bc]
. Each time a character repeats, I want to start a new string.
举个例子,如果我要输入abcaaabbc字符串,我要输出一个字符串数组,等于:[abca, a, ab, bc]。每次一个字符重复,我都想启动一个新的字符串。
Doing this with a loop is possible, of course, but I am wondering if I can achieve it using the String.split()
method. If so - what would the RegEx
be?
当然,使用循环来实现这一点是可能的,但是我想知道是否可以使用String.split()方法实现它。如果是这样,RegEx将会是什么?
2 个解决方案
#1
12
Tokenize the input string where previous character(look-behind (?<=(.))
) is same as next character(look-ahead (?=\\1)
) and \1
captures (.)
.
对输入字符串进行标记,其中前一个字符(查找后(?<=(.)))与下一个字符(查找前一个字符(?=\ 1))和\1捕获(.)。
String str = "abcbabaaabbc";
String regex = "(?<=(.))(?=\\1)";
System.out.println(Arrays.toString(str.split(regex)));
#2
0
From a performance perspective, I would stick with a loop. It runs in O(n) time. The string.split(regex) has been known to be slow. I recently used it in place of a loop and found that it was O(n^2) compared to the O(n) loop.
从性能的角度来看,我将坚持使用循环。它在O(n)时间内运行。斯普利克斯(regex)被认为是缓慢的。我最近用它代替一个循环,发现这是O(n ^ 2)O(n)相比,循环。
K.I.S.S principal works here
K.I.S.年代主要在这里工作
#1
12
Tokenize the input string where previous character(look-behind (?<=(.))
) is same as next character(look-ahead (?=\\1)
) and \1
captures (.)
.
对输入字符串进行标记,其中前一个字符(查找后(?<=(.)))与下一个字符(查找前一个字符(?=\ 1))和\1捕获(.)。
String str = "abcbabaaabbc";
String regex = "(?<=(.))(?=\\1)";
System.out.println(Arrays.toString(str.split(regex)));
#2
0
From a performance perspective, I would stick with a loop. It runs in O(n) time. The string.split(regex) has been known to be slow. I recently used it in place of a loop and found that it was O(n^2) compared to the O(n) loop.
从性能的角度来看,我将坚持使用循环。它在O(n)时间内运行。斯普利克斯(regex)被认为是缓慢的。我最近用它代替一个循环,发现这是O(n ^ 2)O(n)相比,循环。
K.I.S.S principal works here
K.I.S.年代主要在这里工作