How to get URL from String on Android

不想你离开。 提交于 2019-12-19 05:08:42

问题


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.

EditText.setText("hi there this is a URL String http://stackoverflow.com");
EditText.getURLs.toString();

How can I get URL from EditText?


回答1:


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



回答2:


change input type of your EditText ---- android:inputType="textUri"

and get your url using --- String url=edittext.getText().toString();




回答3:


Check this library: (https://github.com/robinst/autolink-java)

  compile "org.nibor.autolink:autolink:0.7.0"

Working fine with Android.

Example:

  LinkExtractor linkExtractor = LinkExtractor.builder()
                    .linkTypes(EnumSet.of(LinkType.URL))
                    .build();
            Iterable<LinkSpan> links = linkExtractor.extractLinks(String_with_Link");
            LinkSpan link = links.iterator().next();
            link.getType();        // LinkType.URL
            link.getBeginIndex();  // 17
            link.getEndIndex();    // 32
            final_Url = String_with_Link.substring(link.getBeginIndex(), link.getEndIndex()); 


来源:https://stackoverflow.com/questions/18630472/how-to-get-url-from-string-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!