English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Expression sous-jacente/Caractère de métacaractère " a | b Correspond à a ou b.
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 the "3codebox"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Nombre de correspondances : ");+count); } }
Résultat de la sortie
Nombre de correspondances : 2
Le programme Java suivant lit la valeur du sexe de l'utilisateur et autorise uniquement M (masculin), F (féminin) ou O (autre).
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { //Correspondance d'expression régulière M ou F ou O- String regex = "M|F|O"; Scanner sc = new Scanner(System.in); System.out.println("Entrez le sexe de l'étudiant :"); String name = sc.nextLine(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(name); if(m.matches()) { System.out.println("Tout est bon"); } else { System.out.println("Entrée incorrecte"); } } }
Entrez le sexe de l'étudiant : M Tout est bon
Entrez le sexe de l'étudiant : masculin Entrée incorrecte