English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
サブエクスプレッション/元文字列「re {n}」は、前の表現がn回目に一致する場所を正確にマッチングします。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "to{1"; String input = "Welcome to w3codebox"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } }
出力結果
Number of matches: 2
Java プログラムがユーザーから年齢値を読み取るとき、それが二桁の数字であることを許可します。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\\d{2"; System.out.println("あなたの年齢を入力してください:"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); if(m.matches()) { System.out.println("Age value accepted"); } else { System.out.println("Age value not accepted"); } } }
あなたの年齢を入力してください: 25 Age value accepted
あなたの年齢を入力してください: 2252 Age value not accepted
あなたの年齢を入力してください: twenty Age value not accepted