我正在尝试检测/匹配以%
开头的编码字符。
我的正则表达式是([%][2-9|A-F][0-9A-F]{1,2})+
在regexr.com上,它工作正常,它符合我的需求。
我使用以下字符串进行测试:caf%C3%A9+100%+noir%C20
和test%C3%A9+%C3%A0+100%
在我的Java代码中,它只返回第一组。
String pattern = "([%][2-9|A-F][0-9A-F]{1,2})+";
Matcher matcher = Pattern.compile(pattern ).matcher(input);
if (matcher.find()) {
for (int i = 0; i < matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
}
caf%C3%A9+100%+noir%C20
的输出是%C3%A9
,而不是%C3%A9
+ %C20
。
因为test%C3%A9+%C3%A0+100%
是%C3%A9
,而不是%C3%A9
+ %C3%A0
发布于 2020-08-11 20:54:09
您正在使用的正则表达式过于复杂。此外,您尝试打印所有匹配的方式也不起作用。试试这个:
String input = "caf%C3%A9+100%+noir%C20";
String pattern = "(?:%[2-9A-F][0-9A-F]{1,2})+";
Matcher matcher = Pattern.compile(pattern ).matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
这将打印:
%C3%A9
%C20
发布于 2020-08-11 20:58:49
基于@41686d6564注释,解决方案是使用while
循环和group(0)
String pattern = "([%][2-9A-F][0-9A-F]{1,2})+";
Matcher matcher = Pattern.compile(pattern).matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(0));
}
https://stackoverflow.com/questions/63358383
复制相似问题