String input = "This is a *2*2*2 test";
String input1 = "This is also a *2*2*2*2 test";
(*2*2*2) または (*2*2*2*2) をキャプチャする正規表現を作成するにはどうすればよいですか?
String input = "This is a *2*2*2 test";
String input1 = "This is also a *2*2*2*2 test";
(*2*2*2) または (*2*2*2*2) をキャプチャする正規表現を作成するにはどうすればよいですか?
これを試すことができます:
Pattern p = Pattern.compile("((\\*2){3,4})");
説明:はパターン\\
にシングルを挿入します。これは、そうでなければワイルドカード文字の一致になる を\
エスケープします。*
文字シーケンス "*2" は、正確に 3 回または 4 回一致します。全体を括弧で囲むと、キャプチャ グループになります。
正規表現を試すことができます:
(\*2){3,4}
一方、パターンの定数を使用して、毎回式を再コンパイルしないようにする必要があります。たとえば、次のようになります。
private static final Pattern REGEX_PATTERN =
Pattern.compile("(\\*2){3,4}");
public static void main(String[] args) {
String input = "This is a *2*2*2 or *2*2*2*2 test";
Matcher matcher = REGEX_PATTERN.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
出力:
*2*2*2
*2*2*2*2