java 截取url参数的正则表达式

 魑魅魍魉龌蹉尴尬 发布于 2022-10-25 10:19

有个url:/result/last/location/{locationId}/*
如何通过 HttpServletRequest 用正则表达式把 {locationId} 中内容获取到
求教!!!!谢谢!!!!!

4 个回答
  • String str = "/result/last/location/{locationId}/*";

        String regex = "/\\{(\\w+)\\}/\\*";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(str);
        while(m.find()){
            System.out.println(m.group());
        }

    不知道这样符不符合你的要求

    2022-10-26 23:07 回答
  • @PathVariable 是比较好的方式

    2022-10-26 23:07 回答
  • "{[}]"
    提取括号的内容的正则你试试看

    2022-10-26 23:07 回答
  • 你可以通过 spring的注解@PathVariable来获得locationId

    public Result method(@PathVariable String locationId)

    你也可以通过string 的split来截取

    public class Test{
      public static void main(String[] args){
        String url = "/result/last/location/{locationId}/*";
       String result =   getStr(url,"location");
        System.out.println(result);
      }
      public static String getStr(String url,String key){
        if(url == null || key == null){
          return "";
        }
        String[] strs = url.split("/");
        for(int i=0;i<strs.length;i++){
            if(strs[i].equals(key)&&i<strs.length-1){
                return strs[i+1];
            }
        }   
        return "";
      }
    }
    
    2022-10-26 23:07 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有