java - 如何从android中的文本中提取所有URL
问题描述
我想使用从给定文本中获取所有 URLPatterns.WEB_URL.matcher(qrText);
我想做的事:
我正在扫描二维码,
- 如果链接包含包含单词“veridoc”的链接,则在 webView 中打开链接
- 如果扫描的文本不是链接或另一个不包含单词“veridoc”的链接,则在 textView 中显示
我试过的:
private void initialize() {
if (getIntent().getStringExtra(Constants.KEY_LINK) != null) {
qrText = getIntent().getStringExtra(Constants.KEY_LINK);
webMatcher = Patterns.WEB_URL.matcher(qrText);
}
if (qrText.contains("veridoc") && webMatcher.matches()) {
//if qr text is veridoc link
Log.e("veridoc link", qrText);
setupWebView(qrText, false);
} else if (webMatcher.matches()) {
//if qr text is link other than veridoc
Log.e("link", qrText);
openInBrowser(qrText);
finish();
} else if (qrText.contains("veridoc") && webMatcher.find()) {
//if qrText contains veridoc link + other text.
String url = webMatcher.group();
if (url.contains("veridoc")) {
Log.e("veridoc link found", url);
setupWebView(url, true);
} else
showQRText(qrText);
} else {
//the qrText neither is a link nor contains any link that contains word veridoc
showQRText(qrText);
}
}
}
在上面的代码中,
setupWebView(String strUrl, boolean isTextAndUrlBoth)
设置 webview 并加载 url 等。openInBrowser(String url)
在浏览器中打开提供的 URL。showQRText(String text)
显示带有格式的 textView 中提供的文本。
问题
当文本包含一些文本和多个链接时,String url = webMatcher.group();
总是获取文本中的第一个链接。
我想要的是
我想要文本中的所有链接,并找出哪些链接包含“veridoc”一词。之后我想调用方法setupWebView(url, true);
。
我正在使用以下链接和文本作为示例
名称:某事 职业:某事 链接1:https://medium.com/@rkdaftary/understanding-git-for-beginners-20d4b55cc72c链接 2: https ://my.veridocglobal.com/login 谁能帮我找到所有文本中存在链接?
解决方案
您可以循环查找以查找不同的网站并使用它设置数组列表
Matcher webMatcher = Patterns.WEB_URL.matcher(input);
ArrayList<String> veridocLinks = new arrayList<>();
ArrayList<String> otherLinks = new arrayList<>();
while (webMatcher.find()){
String res = webMatcher.group();
if(res!= null) {
if(res.contains("veridoc")) veridocLinks.add(res);
else otherLinks.add(res);
}
}
给定一个示例输入,例如:
String input = "http://www.veridoc.com/1 some text http://www.veridoc.com/2 some other text http://www.othersite.com/3";
您的 ArrayLists 将包含:
veridocLinks : "http://www.veridoc.com/1", "http://www.veridoc.com/2"
otherLinks : "http://www.othersite.com/3"
推荐阅读
- php - Ajax 保存到 wordpress 上的服务器
- swift - 如何使用 url 连接视图
- python - 如何适当地大写字符串?
- c++ - 如何将 std::map 值复制到非容器数组中?
- javascript - 单击“显示地图”按钮(类似于Airbnb)后,如何默认打开特定标记的信息框?
- python - 创建一个以字典中的值命名的列表
- python - 如果我们想强制调用父类方法,使用 Classname.method 名称而不是 super() 是唯一的解决方案吗?
- c++ - 将参数包传递给另一个可变参数模板函数时是否必须使用 std::forward
- angular - 为什么将标头添加到角度请求会导致它根本无法正常工作
- javascript - 如何将 JSON.parse 值插入 DOM