English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
サブエクスプレッション/記号「 a | b 「aまたは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("マッチ数の数: "+count); } }
出力結果
マッチ数の数: 2
以下のJavaプログラムはユーザーから性別の値を読み取り、M(男性)、F(女性)またはO(その他)のみを許可します。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main(String args[]) { //正規表現がMまたはFまたはOをマッチします- String regex = "M|F|O"; Scanner sc = new Scanner(System.in); System.out.println("学生の性別を入力してください:"); String name = sc.nextLine(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(name); if(m.matches()) { System.out.println("All OK"); } else { System.out.println("Wrong Input"); } } }
学生の性別を入力してください: M All OK
学生の性別を入力してください: male Wrong Input