[英]Extract encoded strings based on percentage symbol with Regex and Java
我正在嘗試檢測/匹配以%
開頭的編碼字符。
我的正則表達式是([%][2-9|AF][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 caf%C3%A9+100%+noir%C20
的 output 是%C3%A9
而不是%C3%A9
+ %C20
。
對於test%C3%A9+%C3%A0+100%
是%C3%A9
而不是%C3%A9
+ %C3%A0
您使用的正則表達式過於復雜。 此外,您嘗試打印所有匹配項的方式不起作用。 嘗試這個:
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
根據@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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.