简体   繁体   English

仅使用新行正则表达式将字符串拆分为整数

[英]splitting string only integers with new line regular expression

I have an string and try it parsing to string array. 我有一个字符串,并尝试解析为字符串数组。 The string look like: 字符串看起来像:

c: 00000
u: 00001
h: 0001
r: 0010
s: 0011
e: 010
i: 0110
n: 0111

The above example is about only one string reference like String str = testClass.toString(); 上面的例子只是一个字符串引用,如String str = testClass.toString(); I merely want to put the 0 and 1's into a string array. 我只是想将0和1放入一个字符串数组中。

String filtered = str.replaceAll("[^0-1]","");
        String[] numbers = filtered.split("\n");
        for (String a : numbers) {
            System.out.println(a);
        }

I wrote the above code but it gives just one line output. 我写了上面的代码但它只提供了一行输出。 How can it be fixed? 怎么修好?

000000000100010010001101001100111

I intend as 我打算

str[0] = "00000";
...
str[7] = "0111"

The problem is that the '\\n' are also being replaced by an empty string when you call str.replaceAll("[^0-1]","") . 问题是当你调用str.replaceAll("[^0-1]","")时, '\\n'也被空字符串替换。

One possible approach is to replace all chars except digits AND '\\n' : 一种可能的方法是替换除数字AND '\\n'之外的所有字符:

String filtered = str.replaceAll("[^01\n]","");
String[] list = filtered.split("\n");  

Another approach would be to directly split, keeping only "0" and "1" : 另一种方法是直接拆分,只保留"0""1"

String[] list = str.split("[^01]+");

You can strip non numbers and replace with a hyphen - and then split them on - . 您可以删除非数字并用连字符替换-然后将它们拆分-

String filtered = str.replaceAll("[^0-1]+","-");
        String[] numbers = filtered.split("-");
        for (String a : numbers) {
            System.out.println(a);
        }

Just use 只是用

String filtered = str.replaceAll("[^0-1(\n)]","");

instead of 代替

String filtered = `str.replaceAll("[^0-1]","");

Rest of your code is fine. 你的其余代码很好。 Problem is, by using regex [^0-1] you are replacing everything except digits 0 and 1 with empty string. 问题是,通过使用正则表达式[^0-1]您将使用空字符串替换除数字01之外的所有内容。 This in turn replaces \\n as well with empty string "" and hence all 0s and 1s get concatenated. 这反过来也用空字符串""替换\\n ,因此所有0和1都被连接起来。 You actually need to skip digits 0 , 1 and \\n . 实际上,你需要跳过数字01\\n

I would say you can use a single split() to get your array of numbers, but you will have to ignore the first value there (which is empty). 我会说你可以用一个split()来获取你的数字数组,但你必须忽略那里的第一个值(它是空的)。 his will be more efficient than using split + replaceAll() . 他的效率比使用split + replaceAll()更高效。

public static void main(String[] args) {

    String s = "c: 00000" + "\n" + "u: 00001" + "\n" + "h: 0001";
    System.out.println(s);
    String[] arr = s.split("\\D+");
    System.out.println(Arrays.toString(arr));
}

O/P : O / P:

c: 00000
u: 00001
h: 0001
[, 00000, 00001, 0001] // ignore the first empty value.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM