字符更改时拆分字符串。可能的Regex解决方案? [英] Split String when character changes. Possible Regex solution?
问题描述
我有一些 String
只由数字组成,我想在字符变化时拆分。
I have some String
s consisting of only digits, and I want to split it whenever the character changes.
例如:
-
11101100112021120
转到:{111,11,11,2,2,11,2}
- code>222222222转到
{222222222}
-
222222122
转到{222222,1,22}
-
000000000
转到{}
-
0000100000
转到{1}
-
11121222212112133321
到{111,2,1,2222,1,2,11,2 1,333,2,1}
"11101100112021120"
goes to:{"111", "11", "11", "2", "2", "11", "2"}
"222222222"
goes to{"222222222"}
"222222122"
goes to{"222222", "1", "22"}
"000000000"
goes to{}
"0000100000"
goes to{"1"}
"11121222212112133321"
goes to{"111", "2", "1", "2222", "1", "2", "11", "2", "1", "333", "2", "1"}
这样做。
我知道两种方法:只是暴力强制,或者逐节添加。或者,我可以通过删除所有的0,并替换为0,然后添加0,当字符更改,然后只是做一个拆分0,但这两种方式只是看起来愚蠢。
I know two ways to go about this: just brute forcing, or adding section by section. Or, I could go through and remove all 0's and replace with a 0, then add 0's when characters change, and then just do a split on 0's, but both of those ways just look dumb. If anyone has any idea on a better/prettier way to do this, regex or logic, it'd be nice.
推荐答案
如果有任何人有更好/更好的方式来做这个,regex或逻辑,
This seems to work like you expect
data.split("0+|(?<=([1-9]))(?=[1-9])(?!\\1)");
测试:
String[] tests = { "11101100112021120", "222222222", "222222122",
"000000000", "0000100000", "11121222212112133321" };
for (String data : tests) {
System.out.println(data + " ->" + Arrays.toString(data.split("0+|(?<=([1-9]))(?=[1-9])(?!\\1)")));
System.out.println("-----------------------");
}
输出:
11101100112021120 ->[111, 11, 11, 2, 2, 11, 2]
-----------------------
222222222 ->[222222222]
-----------------------
222222122 ->[222222, 1, 22]
-----------------------
000000000 ->[]
-----------------------
0000100000 ->[, 1] // <-- only problem - empty first element
-----------------------
11121222212112133321 ->[111, 2, 1, 2222, 1, 2, 11, 2, 1, 333, 2, 1]
-----------------------
不幸的是,前导零会让数组包含额外的空字符串。要摆脱它,你可以更早删除这些零与 data.replaceFirst(^ 0 +(?= [^ 0]),)
Unfortunately leading zeros will let array to contain additional empty String. To get rid of it you can earlier remove these zeros with data.replaceFirst("^0+(?=[^0])", "")
这篇关于字符更改时拆分字符串。可能的Regex解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!