Android, String.split (String regex) does not break the entire string

I have a problem with String.split (String regular expression). I want to split my string in parts of 4 characters.

String stringa = "1111110000000000"
String [] result = stringa.split("(?<=\\G....)")

When I print the result, I expect 1111,1100,0000,0000, but the result is 1111,110000000000. How can i decide? Thank you

+4
source share
1 answer

Here's a solution without regex -

You start at the end of the line, extract 4 or fewer characters and add them to the list:

public static void main (String[] args) {
    String stringa = "11111110000000000";
    List<String> result = new ArrayList<>();

    for (int endIndex = stringa.length(); endIndex  >= 0; endIndex  -= 4) {
        int beginIndex = Math.max(0, endIndex - 4);
        String str = stringa.substring(beginIndex, endIndex);
        result.add(0, str);
    }

    System.out.println(result);
}

Result:

[1, 1111, 1100, 0000, 0000]
+2
source

Source: https://habr.com/ru/post/1672605/


All Articles