English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Javaのパターンのquote()メソッド及び例

javaのjava.util.regexパッケージは特定のパターンを検索するための様々なクラスを提供します。

このパッケージのパターンクラスは正規表現のコンパイルされた表現です。このクラスのquote()このメソッドは文字列の値を受け取り、指定された文字列に一致するパターンの文字列を返します。他の記号やエスケープシーケンスを追加することで、指定された文字列に影響を与えずにパターンを追加できます。

例1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
   public static void main( String args[] ) {
      //文字列の値を読み取ります
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      System.out.print("Enter the string to be searched: ");
      String regex = Pattern.quote(sc.nextLine());
      System.out.println("pattern string: "+regex);
      //正規表現をコンパイル
      Pattern pattern = Pattern.compile(regex);
      //検索Matcherオブジェクト
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("Match found");
      } else {
         System.out.println("Match not found");
      }
   }
}

出力結果

Enter input string
This is an example program demonstrating the quote() method
Enter the string to be searched: the
pattern string: \Qthe\E
Match found

例2

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class QuoteExample {
   public static void main( String args[] ) {
      String regex = "[aeiou]";
      String input = "Hello how are you welcome to w"3codebox";
      //正規表現をコンパイル
      Pattern.compile(regex);
      regex = Pattern.quote(regex);
      System.out.println("pattern string: "+regex);
      //正規表現をコンパイル
      Pattern pattern = Pattern.compile(regex);
      Matcher matcher = pattern.matcher(input);
      if(matcher.find()) {
         System.out.println("The input string contains vowels");
      } else {
         System.out.println("The input string does not contain vowels");
      }
   }
}

出力結果

pattern string: \Q[aeiou]\E
The input string contains vowels