将正则表达式应用于str.split方法时获取异常 [英] Getting an exception while applying regex to str.split method
问题描述
当我在android外部(即在纯Java环境中)应用此代码时,此代码将完全运行. (有一个链接说这是一个双重问题,但不是).我想知道为什么它在没有android的java中运行,但在android中崩溃.
This code totally runs when I am applying it outside android, that is, in a pure java enviroment. (There is a link that says it is a doublicate of the question, but its not) I want to know why it runs in java without android, but crashes in android.
String[] ar = new String[iters];
ar = myStr.split("(?<=\\G.{16})");
但是,当我在android环境中应用它时,出现以下异常
However, when I apply the same in android enviroment, 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})
推荐答案
可能的原因:
这似乎是您的Android使用的Java版本的错误,已在更高版本的Java版本中得到纠正.
Possible reason:
It looks like a bug of Java version which your Android is using, which was corrected in later Java versions.
\G
可以看作是代表任意一个的锚点
\G
can be considered as anchor which represents either
- 上一场比赛结束
- 字符串的开头(如果尚未找到匹配项)
和任何锚点一样,它是零长度.
and as any anchor it is zero-length.
我怀疑该错误的主要部分是,\G
被后视视为整个先前比赛,而不是其结尾,并且由于先前比赛可能具有任何长度的后视抱怨因为它无法确定明显的最大长度.
I suspect that main part of that bug is that \G
is seen by look-behind as entire previous match, not its end, and since previous match could have any length look-behind complains about it because it can't determine obvious maximal length.
避免split("(?<=\\Gwhatever)")
.
使用Matcher
类代替find()
您要从文本中获取的内容,而不是查找定界符.因此您的代码如下所示:
Instead of finding delimiters, use Matcher
class to find()
things you want to get from text. So your code can look like:
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);
}
输出:
0123456789012345
6789012345678901
2345678901234567
8901234567890123
456789
这篇关于将正则表达式应用于str.split方法时获取异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!