JavaのPatternクラスを使用して文字列内の特定の単語を照合するにはどうすればよいですか?
\ b Java正規表現のメタ文字は単語の境界と一致します。したがって、指定された入力テキストから特定の単語を検索するには、正規表現の単語境界内で必要な単語を-
として指定します。"\\brequired word\\b";
例1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MachingWordExample1 {
public static void main( String args[] ) {
//Reading string value
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.next();
//Regular expression to find digits
String regex = "\\bhello\\b";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} 出力
Enter input string hello welcome to Tutorialspoint Match found
例2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatcherExample2 {
public static void main( String args[] ) {
String input = "This is sample text \n " + "This is second line " + "This is third line";
String regex = "\\bsecond\\b";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} 出力
Match found
-
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() −このメソッドは文字列値を受け入れ、指定された文字列を現在のパターンオブジェクトによって表されるパターンに一致させるマッチャーオブジェクトを作成します。