java 从给定的字符串URL中提取参数值
从给定的url中提取某个参数的值,如:
String url = “https://editor.csdn.net/md/hs/market/category?native_fullscreen=1xxc&hasBack=1&pageIndex=1”;
提取 pageIndex的值为1,native_fullscreen的值为 “1xxc”
实现思路:
1.可以通过字符串截取,url.indexOf(“pageIndex”),url.substring(index, index + 1) 等方式;
缺点是:不够灵活,硬编码多,通用性差。2.通过正则表达式提取。
参考代码
public static String getParamByUrl(String url, String name) {
url += "&";
String pattern = "(\\?|&){1}#{0,1}" + name + "=[a-zA-Z0-9]*(&{1})";
Pattern r = Pattern.compile(pattern);
Matcher matcher = r.matcher(url);
if (matcher.find()) {
return matcher.group(0).split("=")[1].replace("&", "");
} else {
return "";
}
}
demo实例:
public static void main(String []args) {
String url = "/hs/market/category?native_fullscreen=1xxc&hasBack=1&pageIndex=1";
int index = url.indexOf("pageIndex=");
//int num = Integer.valueOf(url.charAt(index + "pageIndex=".length()));
int start = index + "pageIndex=".length();
String sum = url.substring(start, start +1);
System.out.println("---sum:" + sum);
int n = Integer.valueOf(sum);
System.out.println("---index:" + index);
System.out.println("---start:" + start);
System.out.println("---n:" + n);
String page = getParamByUrl(url, "pageIndex");
System.out.println("---page:" + page);
String native_fullscreen= getParamByUrl(url, "native_fullscreen");
System.out.println("---native_fullscreen:" + native_fullscreen);
}
输出:
—sum:1
—index:53
—start:63
—n:1
—page:1
—native_fullscreen:1xxc