需求:
例如:有一段网址如下:
“https://play.vodxc.com/js/m3u8.swf&a=https://youku.comiqiyi.net/20191204/22666_baa03b03/index.m3u8”
怎么才能用正则表达式提取上面字符串的m3u8地址(即a的值的)呢?
最终希望实现的效果:https://youku.comiqiyi.net/20191204/22666_baa03b03/index.m3u8
第一种方法:正则表达式提取
参考代码:
package com.gx.demo;
public class Test4 {
public static void main(String[] args) {
String s = "https://play.vodxc.com/js/m3u8.swf&a=https://youku.comiqiyi.net/20191204/22666_baa03b03/index.m3u8";
//第一种
String reg = "(?:https.*?)(https.*?)";//前一个https不提取
//第二种
String reg2 = ".*?&a=(.*?)"; //a=以后提取信息
//replaceAll(String regex, String replacement) regex: 需要匹配替换的正则;replacement: 将匹配的串替换为此字符串
System.out.println(s.replaceAll(reg, "$1"));//$1取后部分
System.out.println(s.replaceAll(reg2, "$1"));
}
}
输出结果:
https://youku.comiqiyi.net/20191204/22666_baa03b03/index.m3u8
https://youku.comiqiyi.net/20191204/22666_baa03b03/index.m3u8
第二种方法:利用url参数的规则
即可以使用半正则的方式,利用url参数的规则:参数使用&分割的键值对,那么对参数可以使用&分割,如果是键值对,就找参数a的值即可。代码如下:
参考代码:
package com.gx.demo;
public class Test3 {
public static void main(String[] args) {
String test = "https://play.vodxc.com/js/m3u8.swf&a=https://youku.comiqiyi.net/20191204/22666_baa03b03/index.m3u8";
System.out.println(getStr(test, "a"));
}
public static String getStr(String url, String key) {
if (url == null || key == null) {
return "";
}
String[] strs = url.split("[&]");
for (String str : strs) {
String[] args = str.split("[=]");
if (args.length == 2) {
if (args[0].equals(key)) {
return args[1];
}
}
}
return null;
}
}
输出结果:
https://youku.comiqiyi.net/20191204/22666_baa03b03/index.m3u8
以上两种写法都可以实现最终的效果。