How to get URL from String on Android

后端 未结 3 1136
野的像风
野的像风 2021-01-07 12:37

I\'d like to extract URL from hi there this is a URL String http://mytest.com.

I tried to use EditText.getURLs but it didn\'t work for me.



        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 13:12

    Here is the function:

    //Pull all links from the body for easy retrieval
    private ArrayList pullLinks(String text) {
       ArrayList links = new ArrayList();
    
       String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
       Pattern p = Pattern.compile(regex);
       Matcher m = p.matcher(text);
       while(m.find()) {
          String urlStr = m.group();
          if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
             urlStr = urlStr.substring(1, urlStr.length() - 1);
          }
          links.add(urlStr);
       }
       return links;
    }
    

提交回复
热议问题