28

文字列にJava/AndroidのURLが含まれているかどうかを確認する最良の方法は何ですか?文字列に|.com|が含まれているかどうかを確認するのが最善の方法です。.net | .org | .info | .everythingelse |?それともそれを行うためのより良い方法はありますか?

URLはAndroidのEditTextに入力されます。貼り付けられたURLであるか、ユーザーがhttp://を入力したくない手動で入力されたURLである可能性があります...私はURL短縮アプリに取り組んでいます。

4

11 に答える 11

40

最良の方法は、次のような正規表現を使用することです。

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");
}
于 2012-06-13T03:50:27.637 に答える
10

これは、コンストラクターの周りの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();
于 2012-06-13T01:53:49.173 に答える
7

周りを見回した後、try-catchブロックを削除してZaidの答えを改善しようとしました。また、このソリューションは正規表現を使用するため、より多くのパターンを認識します。

したがって、最初にこのパターンを取得します。

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

次に、次のメソッドを使用します(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 + " ");    
        }
    }
于 2015-02-22T02:54:52.047 に答える
3

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;
}
于 2016-10-18T15:27:09.767 に答える
2

古い質問ですが、これを見つけので、共有するのが役立つかもしれないと思いました。Androidに役立つはずです...

于 2015-05-10T10:48:13.017 に答える
1

最初にjava.util.Scannerを使用して、誤検知を生成するが誤検知を生成しない非常にダムなパターンを使用して、ユーザー入力内の候補URLを検索します。次に、@ZedScioが提供する回答のようなものを使用してそれらをフィルタリングします。例えば、

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();
    }
}
于 2012-06-13T01:53:07.067 に答える
1

正規表現を試したり、テスト済みのメソッドを試したりしたくない場合は、Apache Commons Libraryを使用して、特定の文字列がURL/ハイパーリンクであるかどうかを検証できます。以下はその例です。

注意:この例は、「全体」として指定されたテキストがURLであるかどうかを検出するためのものです。通常のテキストとURLの組み合わせを含む可能性のあるテキストの場合、スペースに基づいて文字列を分割し、配列をループして各配列項目を検証するという追加の手順を実行する必要がある場合があります。

Gradleの依存関係:

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

コード:

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

複数のオプションを使用するには、「+」演算子を使用してそれらを追加するだけです

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

詳細については、リンクに詳細が記載されている場合があります。

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

于 2019-08-28T14:20:57.537 に答える
0

この機能は私のために働いています

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

この関数を呼び出す

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

注:-単一のURLを含む文字列をテストしました

于 2017-08-10T07:29:43.223 に答える
0

URLUtil isNetworkUrl(url)またはを使用する必要がありますisValidUrl(url)

于 2020-04-30T19:52:21.177 に答える
0
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");
}
于 2021-01-01T10:53:26.710 に答える
-2

最良の方法は、プロパティの自動リンクをテキストビューに設定することです。Androidは認識して外観を変更し、文字列内の任意の場所でリンクをクリックできるようにします。

android:autoLink = "web"

于 2016-05-19T08:36:34.127 に答える