例を含むJavaのパターンCOMMENTSフィールド
PatternクラスのCOMMENTSフィールドでは、パターンに空白とコメントを含めることができます。これをcompile()メソッドのフラグ値として使用する場合、指定されたパターンでは、空白と#で始まるコメントは無視されます。
例1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input data: ");
String input = sc.nextLine();
//Regular expression to find digits
String regex = "\\d #ignore this comment\n";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
String result = "";
while (matcher.find()) {
count++;
result = result+matcher.group();
}
System.out.println("Number of digits in the given text: "+count);
}
} 出力
Enter input data: sample1 text2 with3 numbers4 in5 between6 Number of digits in the given text: 6
例2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your Date of birth: ");
String dob = sc.nextLine();
//Regular expression to accept date in MM-DD-YYY format
String regex = "^(1[0-2]|0[1-9])/
# For Month\n" + "(3[01]|[12][0-9]|0[1-9])/
# For Date\n" + "[0-9]{4}$ # For Year";
//Creating a Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
//Creating a Matcher object
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if(result) {
System.out.println("Given date of birth is valid");
} else {
System.out.println("Given date of birth is not valid");
}
}
} 出力
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid
-
例を使用したJavaのパターンCANON_EQフィールド
PatternクラスのCANON_EQフィールドは、正規に等しい場合にのみ2つの文字に一致します。これをcompile()メソッドのフラグ値として使用すると、完全な正規分解が等しい場合にのみ、2つの文字が一致します。 正規分解がUnicodeテキスト正規化形式の1つである場合 例1 import java.util.regex.Matcher; import java.util.regex.Pattern; public class CANON_EQ_Example { public static void main( String args[] ) {  
-
例を使用したJavaのパターンpattern()メソッド
java.util.regex javaのパッケージは、文字シーケンスの特定のパターンを見つけるためのさまざまなクラスを提供します。このパッケージのパターンクラスは、正規表現のコンパイル済み表現です。 pattern() パターンの方法 classは、現在のパターンがコンパイルされた文字列形式の正規表現をフェッチして返します。 例1 import java.util.regex.Pattern; public class PatternExample { public static void main(String[] args) {