java 截取url参数的正则表达式
巴扎黑
巴扎黑 2017-04-18 10:22:59
[Java讨论组]

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

巴扎黑
巴扎黑

全部回复(4)
ringa_lee

你可以通过 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 "";
  }
}
迷茫

"{[}]"
提取括号的内容的正则你试试看

怪我咯

@PathVariable 是比较好的方式

高洛峰

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());
    }

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号