[英]Splitting a string around sequences of char in Java
How can I split a string in Java around sequences of a character which are multiple of a particular number? 如何用Java将字符串拆分为多个特定数字的字符序列? Example: I have a binary string
示例:我有一个二进制字符串
101010100010000001110101110111
and I want to split it around sequences of zero which are multiple of 3, ie it should return 我想将其拆分为零的序列,该序列是3的倍数,即它应该返回
[1010101, 1, 1110101110111]
(it should take into regex sequences of zero which are divisible by 3, in this case 000 and 000000) (它应考虑零可被3整除的正则表达式序列,在这种情况下为000和000000)
I tried with split("[0{3}]+")
but it doesn't work. 我尝试了
split("[0{3}]+")
但是它不起作用。
I think split("(0{3})+")
should solve it. 我认为
split("(0{3})+")
应该可以解决。 Putting something between []
means that you are trying to look for certain characters that is in that block. 在
[]
之间插入内容表示您正在尝试查找该块中的某些字符。
UPDATE 更新
If we want what is desired in the comments it should be like this: split("(?<!0)(0{3})+(?!(0{1,2}))")
. 如果我们想要注释中需要的内容,则应为:
split("(?<!0)(0{3})+(?!(0{1,2}))")
。 It is a bit more complex, but it should give the desired output. 它稍微复杂一点,但是应该提供所需的输出。
So lets say we have 100001
as input. 假设我们有
100001
作为输入。 The part (?<!0)
will make sure there is never a 0
at the beginning, otherwise results may look like [10, 1]
. 部分
(?<!0)
将确保开头永远不会为0
,否则结果可能类似于[10, 1]
。 And (?!(0{1,2}))
checks if there are 1 or 2 remaining 0
. 然后
(?!(0{1,2}))
检查是否还有1或2个剩余的0
。
This will give [100001]
with the given input. 这将使
[100001]
具有给定的输入。 With input 1000100001
it will result in [1, 100001]
使用输入
1000100001
,将得到[1, 100001]
Try 尝试
String str = "101010100010000001110101110111";
String[] strArray = str.split("(0{3})+");
System.out.println(Arrays.toString(strArray));
Try 尝试
class Scratch {
public static void main(String[] args) {
String s = "101010100010000001110101110111";
for (String el : s.split("(0{3})+")) {
System.out.println(el);
}
}
}
Use regular expressions for splitting Strings. 使用正则表达式拆分字符串。
It is a very powerful tool. 这是一个非常强大的工具。 Almost a language itself.
几乎是一种语言。
In your case : 在您的情况下 :
s.split("0{3,}") s.split(“ 0 {3,}”)
See you. 再见。
David. 大卫。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.