美文网首页
url参数截取

url参数截取

作者: 霁逸lei | 来源:发表于2022-09-02 16:23 被阅读0次

常规方法截取& = : 后的key-value

String szUrl = "app/page.html?resId=7fa4edfd9ff04e569c5ab664d6f9f803&key1=#!!app.page1:defaultValue#&key2=#!!app.page2:defaultValue#";
HashMap<String, String> cacheMap = new HashMap<>();
cacheMap.put("#!!app.page1","123");
//如果没有替换值,获取默认值替换
if (szUrl.contains("#!!")){
    String urlParam = szUrl.substring(szUrl.indexOf("?") + 1);
    String[] splitParam = urlParam.split("&");
    if (splitParam != null){
        for (String keyParam : splitParam) {
            if (!keyParam.contains("#!!")){
                continue;
            }
            String[] keyValueArray = keyParam.split("=");
            String[] replaceValueArray = keyValueArray[1].split(":");
            String replaceDefault = replaceValueArray[1].replace("#", "");
            for (String webCacheKey : cacheMap.keySet()) {
                if (webCacheKey.equals(replaceValueArray[0])) {
                    replaceDefault = cacheMap.get(webCacheKey);
                }
            }
            szUrl = szUrl.replace(keyValueArray[1],replaceDefault);
        }
    }
}
System.out.println(szUrl);
打印:
app/page.html?resId=7fa4edfd9ff04e569c5ab664d6f9f803&key1=123&key2=defaultValue

正则

szUrl =  "app/page.html?resId=7fa4edfd9ff04e569c5ab664d6f9f803&key1=#!!app.page1:defaultValue#&key2=#!!app.page2:defaultValue#";
String regex = "#!!(.*?)#";
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(szUrl);
while (matcher.find()){
    System.out.println(matcher.group(1));
}

打印:
app.page1:defaultValue
app.page2:defaultValue

相关文章

网友评论

      本文标题:url参数截取

      本文链接:https://www.haomeiwen.com/subject/hibenrtx.html