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

Carattere di escape in espressioni regolari Java a | b

Espressione secondaria/simbolo " a | b Corrisponde a a o b.

Esempio 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      String regex = "Hello|welcome";
      String input = "Hello how are you welcome to w3codebox";
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      while(m.find()) {
         count++;
      }
      System.out.println("Numero di corrispondenze: " + count);
   }
}

Risultato dell'output

Numero di corrispondenze: 2

Esempio 2

Il seguente programma Java legge il valore del sesso dall'utente e consente solo M (maschio), F (femmina) o O (altro).

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main(String args[]) {
      // Espressione regolare che corrisponde a M o F o O-
      String regex = "M|F|O";
      Scanner sc = new Scanner(System.in);
      System.out.println("Inserisci il sesso dello studente:");
      String name = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(name);
      if(m.matches()) {
         System.out.println("Tutto a posto");
      } else {
         System.out.println("Input errato");
      }
   }
}

Output 1

Inserisci il sesso dello studente:
M
Tutto a posto

Output 2

Inserisci il sesso dello studente:
maschio
Input errato
Ti potrebbe interessare