Line split works in Java, does not work in Android

So, I have this logic that breaks a string into 4 characters. Something like that

0108011305080508000000 gives 0108 0113 0508 0508 0000 00

Logic used

String [] splitErrorCode = inputString.split("(?<=\\G....)");

It works fine in Java, but when I run it in Android, I get the wrong output.

0108 011305080508000000

I do not know what is going wrong. After going through the line split function, I realized that Android uses fastSplitwhere, since the Java version has huge split logic.

Shouldn't both functions work the same? Why is this a problem? Any comments / suggestions?

+4
source share
2 answers

\Gin Java added in Java 6 to mimic the Perl construct:

http://perldoc.perl.org/perlfaq6.html#What-good-is-%5CG-in-a-regular-expression:

\G , .

. Python, , , lookbehind. ​​ .

split JDK 7 , . . ( ):

public String[] split(String regex, int limit) {
    /* fastpath if the regex is a
     (1)one-char String and this character is not one of the
        RegEx meta characters ".$|()[{^?*+\\", or
     (2)two-char String and the first char is the backslash and
        the second is not the ascii digit or ascii letter.
     */
    char ch = 0;
    if (((regex.value.length == 1 &&
         ".$|()[{^?*+\\".indexOf(ch = regex.charAt(0)) == -1) ||
         (regex.length() == 2 &&
         /* Fast path checks as documented in the comment */ )
    {
        // Fast path computation redacted!
        String[] result = new String[resultSize];
        return list.subList(0, resultSize).toArray(result);
    }
    return Pattern.compile(regex).split(this, limit);
}

:

public String[] split(String regex, int limit) {
    return Pattern.compile(regex).split(this, limit);
}

, , Android , Java 6. Android , fastSplit Perl, \A.

, - , .

+4

, , (, , ), ; :

private static final Pattern ONE_TO_FOUR_DIGITS = Pattern.compile("\\d{1,4}");

// ...

public List<String> splitErrorCodes(final String input)
{
    final List<String> ret = new ArrayList<>(input.length() / 4 + 1);
    final Matcher m = ONE_TO_FOUR_DIGITS.matcher(input);

    while (m.find())
        ret.add(m.group());

    return ret;
}

, input , . ;)

+3

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


All Articles