首页 > 解决方案 > 如何从android中的文本中提取所有URL

问题描述

我想使用从给定文本中获取所有 URLPatterns.WEB_URL.matcher(qrText);

我想做的事:

我正在扫描二维码,

我试过的:

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

在上面的代码中,

问题

当文本包含一些文本和多个链接时,String url = webMatcher.group();总是获取文本中的第一个链接。

我想要的是

我想要文本中的所有链接,并找出哪些链接包含“veridoc”一词。之后我想调用方法setupWebView(url, true);

我正在使用以下链接和文本作为示例

名称:某事 职业:某事 链接1:https://medium.com/@rkdaftary/understanding-git-for-beginners-20d4b55cc72c链接 2: https ://my.veridocglobal.com/login 谁能帮我找到所有文本中存在链接?

标签: javaandroidregex

解决方案


您可以循环查找以查找不同的网站并使用它设置数组列表

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"

推荐阅读