JavaRegExを使用して固定文字セットを照合する方法
文字クラスを使用すると、固定された文字セットから1つの文字を受け入れることができます。たとえば、
-
「[tmp]」という表現 」は文字tまたは、mまたは、pに一致します。
-
「[^tp]」という表現 」は、tまたはp以外の文字と一致します。
例1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression to match the characters t or, m or, p
String regex = "[tmp]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Occurrences: "+count);
}
} 出力
Enter a String hello how are you welcome to tutorialspoint Occurrences :6
例2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "[^abcdef]";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Occurrences :"+count);
}
} 出力
Enter a String Hello how are you welcome to tutorialspoint Occurrences :36
-
JavaRegExを使用して任意の文字を照合する方法
メタ文字「。」 Javaの正規表現は、任意の文字(単一)に一致します。アルファベット、数字、または任意の特殊文字にすることができます。 例1 import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user
-
Javaで正規表現を使用して文字列からHTMLタグを抽出するにはどうすればよいですか?
javaのjava.util.regexパッケージは、文字シーケンスの特定のパターンを見つけるためのさまざまなクラスを提供します。 パターン このパッケージのクラスは、正規表現のコンパイル済み表現です。正規表現を文字列と照合するために、このクラスは2つのメソッド、つまり-を提供します。 compile() −このメソッドは、正規表現を表す文字列を受け入れ、Patternクラスのオブジェクトを返します。 matcher() −このメソッドは文字列値を受け入れ、指定された文字列を現在のパターンオブジェクトによって表されるパターンに一致させるマッチャーオブジェクトを作成します。