Java正規表現
正規表現とは何ですか?
正規表現は、検索パターンを形成する一連の文字です。テキスト内のデータを検索する場合、この検索パターンを使用して、検索対象を説明できます。
正規表現は、単一の文字でも、より複雑なパターンでもかまいません。
正規表現を使用して、すべてのタイプのテキスト検索およびテキスト置換 操作を実行できます。
Javaには組み込みの正規表現クラスはありませんが、java.util.regex
パッケージをインポートして正規表現を操作できます。パッケージには、次のクラスが含まれています。
Pattern
クラス-パターンを定義します(検索で使用されます)Matcher
クラス-パターンの検索に使用されますPatternSyntaxException
クラス-正規表現パターンの構文エラーを示します
例
文中に「w3schools」という単語が含まれているかどうかを調べます。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("Visit W3Schools!");
boolean matchFound = matcher.find();
if(matchFound) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}
// Outputs Match found
例の説明
この例では、「w3schools」という単語が文の中で検索されています。
まず、Pattern.compile()
メソッドを使用してパターンを作成します。最初のパラメーターは検索対象のパターンを示し、2番目のパラメーターには検索で大文字と小文字を区別しないことを示すフラグがあります。2番目のパラメーターはオプションです。
このmatcher()
メソッドは、文字列内のパターンを検索するために使用されます。実行された検索に関する情報を含むMatcherオブジェクトを返します。
このfind()
メソッドは、文字列でパターンが見つかった場合はtrueを返し、見つからなかった場合はfalseを返します。
フラグ
メソッドのフラグはcompile()
、検索の実行方法を変更します。それらのいくつかを次に示します。
Pattern.CASE_INSENSITIVE
-検索を実行するとき、文字の大文字小文字は無視されます。Pattern.LITERAL
-パターン内の特殊文字は特別な意味を持たず、検索を実行するときに通常の文字として扱われます。Pattern.UNICODE_CASE
-フラグと一緒に使用してCASE_INSENSITIVE
、英語のアルファベット以外の文字の大文字小文字も無視します
正規表現パターン
メソッドの最初のパラメーターはPattern.compile()
パターンです。何が検索されているかを説明します。
角かっこは、文字の範囲を見つけるために使用されます。
Expression | Description |
---|---|
[abc] | Find one character from the options between the brackets |
[^abc] | Find one character NOT between the brackets |
[0-9] | Find one character from the range 0 to 9 |
メタ文字
メタ文字は、特別な意味を持つ文字です。
Metacharacter | Description |
---|---|
| | Find a match for any one of the patterns separated by | as in: cat|dog|fish |
. | Find just one instance of any character |
^ | Finds a match as the beginning of a string as in: ^Hello |
$ | Finds a match at the end of the string as in: World$ |
\d | Find a digit |
\s | Find a whitespace character |
\b | Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b |
\uxxxx | Find the Unicode character specified by the hexadecimal number xxxx |
量指定子
数量詞は数量を定義します。
Quantifier | Description |
---|---|
n+ | Matches any string that contains at least one n |
n* | Matches any string that contains zero or more occurrences of n |
n? | Matches any string that contains zero or one occurrences of n |
n{x} | Matches any string that contains a sequence of X n's |
n{x,y} | Matches any string that contains a sequence of X to Y n's |
n{x,} | Matches any string that contains a sequence of at least X n's |
注:式で特殊文字の1つを検索する必要がある場合は、円記号(\)を使用してそれらをエスケープできます。Javaでは、文字列のバックスラッシュはそれ自体でエスケープする必要があるため、特殊文字をエスケープするには2つのバックスラッシュが必要です。たとえば、1つ以上の疑問符を検索するには、次の式を使用できます: "\\?"