Getting exception when applying regex to str.split method

This code fully works when I use it outside of android, i.e. in a clean java environment. (There is a link saying that this is a duplicate of the question, but it is not there) I want to know why it works in java without an android, but it crashes in android.

String[] ar = new String[iters]; ar = myStr.split("(?<=\\G.{16})"); 

However, when I apply the same in Android environment, I get the following exception

 04-13 13:50:22.255: E/AndroidRuntime(2147): FATAL EXCEPTION: main 04-13 13:50:22.255: E/AndroidRuntime(2147): java.util.regex.PatternSyntaxException: Look-behind pattern matches must have a bounded maximum length near index 12: 04-13 13:50:22.255: E/AndroidRuntime(2147): (?<=\G.{16}) 
+1
java android regex
Apr 13 '15 at 10:55
source share
1 answer

Possible reason:

This is similar to the Java version error your Android uses, which has been fixed in later versions of Java.

\G can be thought of as an anchor that represents

  • end of previous match
  • beginning of line (if no match is found)

and like any zero length anchor.

I suspect that the main part of this error is that \G perceived as the inverse of the whole previous match, and not its end, and since the previous match may have any appearance, complains about it because it cannot determine obvious maximum length.

Way around.

Avoid split("(?<=\\Gwhatever)") .

Instead of looking for delimiters, use the Matcher class to find() things you want from the text. So your code might look like this:

 String myStr = "0123456789012345678901234567890123456789012345678901234567890123456789"; Matcher m = Pattern.compile(".{1,16}").matcher(myStr); while (m.find()) { String s = m.group(); //do what you want with current token stored in `s` System.out.println(s); } 

Output:

 0123456789012345 6789012345678901 2345678901234567 8901234567890123 456789 
+1
Apr 13 '15 at 11:27
source share



All Articles