我想从hi there this is a URL String http://mytest.com
中提取网址。
我尝试使用EditText.getURLs,但它对我不起作用。
EditText.setText("hi there this is a URL String http://stackoverflow.com");
EditText.getURLs.toString();
如何从EditText获取网址?
答案 0 :(得分:12)
这是功能:
//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;
}
答案 1 :(得分:1)
更改EditText的输入类型---- android:inputType =“textUri”
并使用--- String url = edittext.getText()。toString();
答案 2 :(得分:0)
检查此库:(https://github.com/robinst/autolink-java)
compile "org.nibor.autolink:autolink:0.7.0"
适用于Android。
示例:
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());