简体   繁体   English

检查 String 是否包含 Java/Android 中的 URL 的最佳方法是什么?

[英]What's the best way to check if a String contains a URL in Java/Android?

What's the best way to check if a String contains a URL in Java/Android?检查 String 是否包含 Java/Android 中的 URL 的最佳方法是什么? Would the best way be to check if the string contains |.com |最好的方法是检查字符串是否包含 |.com | .net |.org |.info |.everythingelse|? .net |.org |.info |.everythingelse|? Or is there a better way to do it?或者有更好的方法吗?

The url is entered into a EditText in Android, it could be a pasted url or it could be a manually entered url where the user doesn't feel like typing in http://... I'm working on a URL shortening app. url 输入到 Android 中的 EditText 中,它可以是粘贴的 url,也可以是手动输入的 url,用户不想输入 http://... 我正在开发 URL 缩短应用程序.

Best way would be to use regular expression, something like below:最好的方法是使用正则表达式,如下所示:

public static final String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";

Pattern p = Pattern.compile(URL_REGEX);
Matcher m = p.matcher("example.com");//replace with string to compare
if(m.find()) {
    System.out.println("String contains URL");
}

This is simply done with a try catch around the constructor (this is necessary either way).这只需围绕构造函数进行 try catch 即可完成(无论哪种方式都是必要的)。

String inputUrl = getInput();
if (!inputUrl.contains("http://"))
    inputUrl = "http://" + inputUrl;

URL url;
try {
    url = new URL(inputUrl);
} catch (MalformedURLException e) {
    Log.v("myApp", "bad url entered");
}
if (url == null)
    userEnteredBadUrl();
else
    continue();

After looking around I tried to improve Zaid's answer by removing the try-catch block.环顾四周后,我试图通过删除 try-catch 块来改进 Zaid 的回答。 Also, this solution recognizes more patterns as it uses a regex.此外,此解决方案使用正则表达式可识别更多模式。

So, firstly get this pattern:所以,首先得到这个模式:

// Pattern for recognizing a URL, based off RFC 3986
private static final Pattern urlPattern = Pattern.compile(
    "(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
            + "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
            + "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);

Then, use this method (supposing str is your string):然后,使用此方法(假设str是您的字符串):

    // separate input by spaces ( URLs don't have spaces )
    String [] parts = str.split("\\s+");

    // get every part
    for( String item : parts ) {
        if(urlPattern.matcher(item).matches()) { 
            //it's a good url
            System.out.print("<a href=\"" + item + "\">"+ item + "</a> " );                
        } else {
           // it isn't a url
            System.out.print(item + " ");    
        }
    }

Based on Enkk's answer, i present my solution:根据 Enkk 的回答,我提出了我的解决方案:

public static boolean containsLink(String input) {
    boolean result = false;

    String[] parts = input.split("\\s+");

    for (String item : parts) {
        if (android.util.Patterns.WEB_URL.matcher(item).matches()) {
            result = true;
            break;
        }
    }

    return result;
}

Old question, but found this , so I thought it might be useful to share.老问题,但发现了这个,所以我认为分享可能有用。 Should help for Android...应该对 Android 有帮助...

I would first use java.util.Scanner to find candidate URLs in the user input using a very dumb pattern that will yield false positives, but no false negatives.我会首先使用 java.util.Scanner 在用户输入中使用一种非常愚蠢的模式查找候选 URL,这种模式会产生误报,但不会产生漏报。 Then, use something like the answer @ZedScio provided to filter them down.然后,使用@ZedScio 提供的答案之类的东西来过滤它们。 For example,例如,

Pattern p = Pattern.compile("[^.]+[.][^.]+");
Scanner scanner = new Scanner("Hey Dave, I found this great site called blah.com you should visit it");
while (scanner.hasNext()) {
    if (scanner.hasNext(p)) {
        String possibleUrl = scanner.next(p);
        if (!possibleUrl.contains("://")) {
            possibleUrl = "http://" + possibleUrl;
        }

        try {
            URL url = new URL(possibleUrl);
            doSomethingWith(url);
        } catch (MalformedURLException e) {
            continue;
        }
    } else {
        scanner.next();
    }
}

If you don't want to experiment with regular expressions and try a tested method, you can use the Apache Commons Library and validate if a given string is an URL/Hyperlink or not.如果您不想试验正则表达式并尝试一种经过测试的方法,您可以使用 Apache Commons Library 并验证给定的字符串是否为 URL/超链接。 Below is the example.下面是例子。

Please note: This example is to detect if a given text as a 'whole' is a URL.请注意:此示例用于检测作为“整体”的给定文本是否为 URL。 For text that may contain a combination of regular text along with URLs, one might have to perform an additional step of splitting the string based on spaces and loop through the array and validate each array item.对于可能包含常规文本和 URL 组合的文本,可能必须执行额外的步骤,即根据空格拆分字符串并循环遍历数组并验证每个数组项。

Gradle dependency:摇篮依赖:

implementation 'commons-validator:commons-validator:1.6'

Code:代码:

import org.apache.commons.validator.routines.UrlValidator;

// Using the default constructor of UrlValidator class
public boolean URLValidator(String s) {
    UrlValidator urlValidator = new UrlValidator();
    return urlValidator.isValid(s);
}

// Passing a scheme set to the constructor
public boolean URLValidator(String s) {
    String[] schemes = {"http","https"}; // add 'ftp' is you need
    UrlValidator urlValidator = new UrlValidator(schemes);
    return urlValidator.isValid(s);
}

// Passing a Scheme set and set of Options to the constructor
public boolean URLValidator(String s) {
    String[] schemes = {"http","https"}; // add 'ftp' is you need. Providing no Scheme will validate for http, https and ftp
    long options = UrlValidator.ALLOW_ALL_SCHEMES + UrlValidator.ALLOW_2_SLASHES + UrlValidator.NO_FRAGMENTS;
    UrlValidator urlValidator = new UrlValidator(schemes, options);
    return urlValidator.isValid(s);
}

// Possible Options are:
// ALLOW_ALL_SCHEMES
// ALLOW_2_SLASHES
// NO_FRAGMENTS
// ALLOW_LOCAL_URLS

To use multiple options, just add them with the '+' operator要使用多个选项,只需使用“+”运算符添加它们

If you need to exclude project level or transitive dependencies in the grade while using the Apache Commons library, you may want to do the following (Remove whatever is required from the list):如果您需要在使用 Apache Commons 库时排除项目级别或等级中的传递依赖项,您可能需要执行以下操作(从列表中删除所需的任何内容):

implementation 'commons-validator:commons-validator:1.6' {
    exclude group: 'commons-logging'
    exclude group: 'commons-collections'
    exclude group: 'commons-digester'
    exclude group: 'commons-beanutils'
}

For more information, the link may provide some details.有关更多信息,链接可能会提供一些详细信息。

http://commons.apache.org/proper/commons-validator/dependencies.html http://commons.apache.org/proper/commons-validator/dependencies.html

This function is working for me这个功能对我有用

private boolean containsURL(String content){
    String REGEX = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
    Pattern p = Pattern.compile(REGEX,Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(content);
    return m.find();
}

Call this function调用这个函数

boolean isContain = containsURL("Pass your string here...");
Log.d("Result", String.valueOf(isContain));

NOTE:- I have tested string containing single url注意:- 我已经测试了包含单个 url 的字符串

You need to use URLUtil isNetworkUrl(url) or isValidUrl(url)您需要使用URLUtil isNetworkUrl(url)isValidUrl(url)

public boolean isURL(String text) {
    return text.length() > 3 && text.contains(".")
            && text.toCharArray()[text.length() - 1] != '.' && text.toCharArray()[text.length() - 2] != '.'
            && !text.contains(" ") && !text.contains("\n");
}

The best way is to to set the property autolink to your textview, Android will recognize, change the appearance and make clickable a link anywhere inside the string.最好的方法是将属性自动链接设置为您的文本视图,Android 将识别、更改外观并使字符串内任何位置的链接都可点击。

android:autoLink="web"机器人:autoLink =“网络”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java - 检查STRING是否只包含某些字符的最佳方法是什么? - Java - what is the best way to check if a STRING contains only certain characters? 在 Java 中检查 String 是否代表整数的最佳方法是什么? - What's the best way to check if a String represents an integer in Java? 检查字符是否是Java中的元音的最佳方法是什么? - What's the best way to check if a character is a vowel in Java? 在 Java 中检查对象及其成员为空的最佳方法是什么 - What is the best way to check object and it's members are null in Java 在 Java 中检查字符串不为空且不为空的最佳方法是什么? - What is the best way to check string not null and not empty in Java? 在 Java 中,读取 url 并将其拆分为多个部分的最佳方法是什么? - In java, what's the best way to read a url and split it into its parts? 在 Java 中构建一串分隔项的最佳方法是什么? - What's the best way to build a string of delimited items in Java? 如何检查字符串是否包含java中的url - How to check if a string contains url in java 使用 Java 保护查询字符串的最佳方法是什么? - What's the best way to secure a query string with Java? 检查列表是否包含指定项目以外的项目的最佳方法是什么? - What’s the best way to check if a list contains an item other than specified item?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM