Java-regular-expressions
Java-正規表現
Javaは、正規表現とのパターンマッチングのためにjava.util.regexパッケージを提供します。 Javaの正規表現はPerlプログラミング言語に非常に似ており、非常に簡単に習得できます。
正規表現は、パターンに保持されている特殊な構文を使用して、他の文字列または文字列のセットを一致または検索するのに役立つ特殊な文字シーケンスです。 テキストおよびデータの検索、編集、または操作に使用できます。
java.util.regexパッケージは、主に次の3つのクラスで構成されています-
- パターンクラス-パターンオブジェクトは、正規表現のコンパイル済み表現です。 Patternクラスは、パブリックコンストラクターを提供しません。 パターンを作成するには、最初にパブリックstatic * compile()*メソッドの1つを呼び出してから、Patternオブジェクトを返す必要があります。 これらのメソッドは、最初の引数として正規表現を受け入れます。
- * Matcherクラス*-Matcherオブジェクトは、パターンを解釈し、入力文字列に対して一致操作を実行するエンジンです。 Patternクラスと同様に、Matcherはパブリックコンストラクターを定義しません。 Matcherオブジェクトを取得するには、Patternオブジェクトで* matcher()*メソッドを呼び出します。
- PatternSyntaxException -PatternSyntaxExceptionオブジェクトは、正規表現パターンの構文エラーを示す未チェックの例外です。
グループのキャプチャ
キャプチャグループは、複数の文字を単一のユニットとして扱う方法です。 グループ化する文字を括弧のセット内に配置することで作成されます。 たとえば、正規表現(dog)は、「d」、「o」、および「g」の文字を含む単一のグループを作成します。
キャプチャグループには、左から右に向かって括弧を数えることで番号が付けられます。 式((A)(B(C)))では、例えば、4つのそのようなグループがあります-
- ((A)(B(C))))
- (A)
- (紀元前))
- ©
式に存在するグループの数を調べるには、マッチャーオブジェクトでgroupCountメソッドを呼び出します。 groupCountメソッドは、マッチャーのパターンに存在するキャプチャグループの数を示す int を返します。
式0を常に表す特別なグループgroup 0もあります。 このグループは、groupCountによって報告された合計には含まれません。
例
次の例は、指定された英数字文字列から数字列を見つける方法を示しています-
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
public static void main( String args[] ) {
//String to be scanned to find the pattern.
String line = "This order was placed for QT3000! OK?";
String pattern = "(.*)(\\d+)(.*)";
//Create a Pattern object
Pattern r = Pattern.compile(pattern);
//Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
}else {
System.out.println("NO MATCH");
}
}
}
これは、次の結果を生成します-
- 出力 *
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT300
Found value: 0
正規表現の構文
これは、Javaで使用可能なすべての正規表現メタ文字構文をリストした表です-
Subexpression | Matches |
---|---|
^ | Matches the beginning of the line. |
$ | Matches the end of the line. |
. | Matches any single character except newline. Using* m* option allows it to match the newline as well. |
[…] | Matches any single character in brackets. |
[^…] | Matches any single character not in brackets. |
\A | Beginning of the entire string. |
\z | End of the entire string. |
\Z | End of the entire string except allowable final line terminator. |
re * | Matches 0 or more occurrences of the preceding expression. |
rePLUS | Matches 1 or more of the previous thing. |
re? | Matches 0 or 1 occurrence of the preceding expression. |
re\{ n} | Matches exactly n number of occurrences of the preceding expression. |
re\{ n,} | Matches n or more occurrences of the preceding expression. |
re\{ n, m} | Matches at least n and at most m occurrences of the preceding expression. |
a | b |
Matches either a or b. | (re) |
Groups regular expressions and remembers the matched text. | (?: re) |
Groups regular expressions without remembering the matched text. | (?> re) |
Matches the independent pattern without backtracking. | \w |
Matches the word characters. | \W |
Matches the nonword characters. | \s |
Matches the whitespace. Equivalent to [\t\n\r\f]. | \S |
Matches the nonwhitespace. | \d |
Matches the digits. Equivalent to [0-9]. | \D |
Matches the nondigits. | \A |
Matches the beginning of the string. | \Z |
Matches the end of the string. If a newline exists, it matches just before newline. | \z |
Matches the end of the string. | \G |
Matches the point where the last match finished. | \n |
Back-reference to capture group number "n". | \b |
Matches the word boundaries when outside the brackets. Matches the backspace (0x08) when inside the brackets. | \B |
Matches the nonword boundaries. | \n, \t, etc. |
Matches newlines, carriage returns, tabs, etc. | \Q |
Escape (quote) all characters up to \E. | \E |
マッチャークラスのメソッド
ここに便利なインスタンスメソッドのリストがあります-
インデックスメソッド
インデックスメソッドは、入力文字列で一致が見つかった場所を正確に示す便利なインデックス値を提供します-
Sr.No. | Method & Description |
---|---|
1 |
前のマッチの開始インデックスを返します。 |
2 |
public int start(int group) 前の一致操作中に特定のグループによってキャプチャされたサブシーケンスの開始インデックスを返します。 |
3 |
public int end() 最後の文字が一致した後のオフセットを返します。 |
4 |
public int end(int group) 前の一致操作中に特定のグループによってキャプチャされたサブシーケンスの最後の文字の後のオフセットを返します。 |
研究方法
研究方法は、入力文字列を確認し、パターンが見つかったかどうかを示すブール値を返します-
Sr.No. | Method & Description |
---|---|
1 |
public boolean lookingAt() 領域の先頭から開始して、パターンに対して入力シーケンスを一致させようとします。 |
2 |
public boolean find() パターンに一致する入力シーケンスの次のサブシーケンスを見つけようとします。 |
3 |
public boolean find(int start) このマッチャーをリセットし、指定されたインデックスから開始して、パターンに一致する入力シーケンスの次のサブシーケンスを見つけようとします。 |
4 |
public boolean matches() 領域全体をパターンと一致させようとします。 |
交換方法
置換方法は、入力文字列内のテキストを置換するための便利な方法です-
Sr.No. | Method & Description |
---|---|
1 |
public Matcher appendReplacement(StringBuffer sb, String replacement) 非終端追加および置換ステップを実装します。 |
2 |
public StringBuffer appendTail(StringBuffer sb) ターミナルの追加および交換手順を実装します。 |
3 |
public String replaceAll(String replacement) パターンに一致する入力シーケンスのすべてのサブシーケンスを、指定された置換文字列に置き換えます。 |
4 |
public String replaceFirst(String replacement) パターンに一致する入力シーケンスの最初のサブシーケンスを、指定された置換文字列に置き換えます。 |
5 |
public static String quoteReplacement(String s) 指定された文字列のリテラル置換文字列を返します。 このメソッドは、MatcherクラスのappendReplacementメソッドでリテラル置換 s として機能するストリングを生成します。 |
開始および終了メソッド
以下は、単語「cat」が入力文字列に出現する回数をカウントする例です-
例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
private static final String REGEX = "\\bcat\\b";
private static final String INPUT = "cat cat cat cattie cat";
public static void main( String args[] ) {
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); //get a matcher object
int count = 0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}
これは、次の結果を生成します-
出力
Match number 1
start(): 0
end(): 3
Match number 2
start(): 4
end(): 7
Match number 3
start(): 8
end(): 11
Match number 4
start(): 19
end(): 22
この例では、単語の境界を使用して、文字 "c" "a" "t"が長い単語の単なる部分文字列ではないことを確認できます。 また、入力文字列のどこで一致したかに関するいくつかの有用な情報も提供します。
startメソッドは、前の一致操作中に特定のグループによってキャプチャされたサブシーケンスの開始インデックスを返し、終了は一致した最後の文字のインデックスに1を加えたものを返します。
マッチとlookingAtメソッド
matchesメソッドとlookingAtメソッドは両方とも、入力シーケンスをパターンと一致させようとします。 しかし、違いは、一致では入力シーケンス全体が一致する必要があるのに対して、lookingAtでは一致しないことです。
どちらの方法も常に入力文字列の先頭から始まります。 ここに機能を説明する例があります-
例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
private static final String REGEX = "foo";
private static final String INPUT = "fooooooooooooooooo";
private static Pattern pattern;
private static Matcher matcher;
public static void main( String args[] ) {
pattern = Pattern.compile(REGEX);
matcher = pattern.matcher(INPUT);
System.out.println("Current REGEX is: "+REGEX);
System.out.println("Current INPUT is: "+INPUT);
System.out.println("lookingAt(): "+matcher.lookingAt());
System.out.println("matches(): "+matcher.matches());
}
}
これは、次の結果を生成します-
出力
Current REGEX is: foo
Current INPUT is: fooooooooooooooooo
lookingAt(): true
matches(): false
replaceFirstおよびreplaceAllメソッド
replaceFirstメソッドとreplaceAllメソッドは、特定の正規表現に一致するテキストを置き換えます。 名前が示すように、replaceFirstは最初の出現を置換し、replaceAllはすべての出現を置換します。
ここに機能を説明する例があります-
例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
private static String REGEX = "dog";
private static String INPUT = "The dog says meow. " + "All dogs say meow.";
private static String REPLACE = "cat";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
//get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
これは、次の結果を生成します-
出力
The cat says meow. All cats say meow.
appendReplacementおよびappendTailメソッド
Matcherクラスは、テキスト置換のためのappendReplacementおよびappendTailメソッドも提供します。
ここに機能を説明する例があります-
例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
private static String REGEX = "a*b";
private static String INPUT = "aabfooaabfooabfoob";
private static String REPLACE = "-";
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
//get a matcher object
Matcher m = p.matcher(INPUT);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, REPLACE);
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
これは、次の結果を生成します-
- 出力 *
-foo-foo-foo-
PatternSyntaxExceptionクラスメソッド
PatternSyntaxExceptionは、正規表現パターンの構文エラーを示す未チェックの例外です。 PatternSyntaxExceptionクラスは、次のメソッドを提供して、何がうまくいかなかったかを判断するのに役立ちます-
Sr.No. | Method & Description |
---|---|
1 |
エラーの説明を取得します。 |
2 |
public int getIndex() エラーインデックスを取得します。 |
3 |
public String getPattern() エラーのある正規表現パターンを取得します。 |
4 |
public String getMessage() 構文エラーとそのインデックスの説明、エラーのある正規表現パターン、およびパターン内のエラーインデックスの視覚的表示を含む複数行の文字列を返します。 |