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

Abbinamento delle stringhe con Java regex indipendentemente dalla differenza di maiuscole e minuscole.

Il metodo compile della classe pattern accetta due parametri -

  • Rappresenta il valore stringa dell'espressione regolare.

  • Un valore intero, è un campo della classe Pattern.

Il campo CASE_INSENSITIVE della classe Pattern abbinato ai caratteri indipendentemente dal caso.compile()Se passati al metodo insieme all'espressione regolare, verranno abbinati entrambi i casi di caratteri.

Esempio 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input data: ");
      String input = sc.nextLine();
      //正则表达式以查找所需字符
      String regex = "test";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex); //, Pattern.CASE_INSENSITIVE);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number of occurrences: " + count);
   }
}

Output result

Enter input data:
test TEST Test sample data
Number of occurrences: 3

Example 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VerifyBoolean {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string value: ");
      String str = sc.next();
      Pattern pattern = Pattern.compile("true|false", Pattern.CASE_INSENSITIVE);
      Matcher matcher = pattern.matcher(str);
      if(matcher.matches()){
         System.out.println("Given string is a boolean type");
      } else {
         System.out.println("Given string is not a boolean type");
      }
   }
}

Output result

Enter a string value:
TRUE
Given string is a boolean type
Ti potrebbe interessare