我知道这是一个极端情况,但我遇到过使用正则表达式和可变组数的代码
根据 docs这是合法的:
The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.
但是,当我尝试将其与 unicode 符号“笑脸笑脸”(U+1F601) 一起使用时,我得到 StringIndexOutOfBoundsException。
这是规范所期望的还是错误?
测试代码如下:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestEmoji {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(A.)* EEE");
testGroups(pattern, "ACAB EEE");
testGroups(pattern, "ABACA\uD83D\uDE01");
}
public static void testGroups(Pattern pattern, String s) {
Matcher matcher = pattern.matcher(s);
if (matcher.matches()) {
System.out.println("matches");
System.out.println(matcher.groupCount());
for (int i = 1; i <= matcher.groupCount(); ++i) {
System.out.println(matcher.group(i));
}
}
}
}
和异常:
matches
1
AB
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
at java.lang.String.charAt(String.java:658)
at java.util.regex.Pattern$Slice.match(Pattern.java:3867)
at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4382)
at java.util.regex.Pattern$GroupCurly.match0(Pattern.java:4354)
at java.util.regex.Pattern$GroupCurly.match(Pattern.java:4304)
at java.util.regex.Matcher.match(Matcher.java:1221)
at java.util.regex.Matcher.matches(Matcher.java:559)
at TestEmoji.testGroups(TestEmoji.java:19)
at TestEmoji.main(TestEmoji.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
最佳答案
在 Java Bugs 数据库中进行了一些挖掘之后,我发现了它:
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8007395
JDK-8007395:当输入字符串包含替代 UTF-16 字符时,Match.find() 中出现 StringIndexOutofBoundsException
关于java - 具有可变组数的正则表达式中的表情符号 Unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21633109/