最近项目里做关于UC浏览器,QQ浏览器分享到我们应用的功能,返回的数据中包含这样一串string:
现在想把URL截出来,就需要用到正则表达式,从浏览器里分享出来的字符串都有一个规范就是在URL的前后会与其他文本留一个空格,So我的思路是先截出来http开头到字符串末尾的文本,然后利用正则匹配字符串截取第一个URL。
我的代码
public static String getFirstURLFromTextContent(String textContent){
String result = null;
List<String> ls=new ArrayList<String>();
if (textContent.indexOf("http")!= -1){
String subTextContent = textContent.substring(textContent.indexOf("http"));
String formatString = "((https|http|ftp|rtsp|mms)?:\\/\\/)[^\\s]+";
Pattern pattern = Pattern.compile(formatString);
Matcher matcher = pattern.matcher(subTextContent);
while(matcher.find()){
ls.add(matcher.group());
}
result = ls.get(0);
}
return result;
}
接下来重点看正则表达式,发现这个网站非常的好用,尤其是对于正则表达式一无所知的小白很是实用:正则测试网站
网站内容很实用,基本一看就会,我们只需要确认正则是正确的,就可以生成相应的代码在我们工程用使用了。(天下武功,唯快不破)关于正则更多的功能,需要自己研究和学习,这里到此为止。