正規表現を試したり、テスト済みのメソッドを試したりしたくない場合は、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