English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
子表达式/元字符" re {n, m} 至少n个和最多m个与前面的表达式的匹配。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main(String args[]) { String regex = "xyy{2,4"; String input = "xxyyzxxyyyyxyyzxxyyzz"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches:")+count); } }
출력 결과
일치 횟수: 1
다음 Java 프로그램은 사용자로부터 이름 값을 읽고, 다음과 같은 이름만 허용합니다1까지20개의 캐릭터.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main(String args[] ) { //캐릭터가 최소한 일치하는 정규 표현식 1 almost 20 String regex = "[a-zA-Z]{1,20}"; 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("이름이 적절합니다"); } else { System.out.println("이름이 부적절합니다"); } } }
학생 이름을 입력하세요: Mouktika 이름이 적절합니다
학생 이름을 입력하세요: 카 34 이름이 부적절합니다
학생 이름을 입력하세요: Sri Veera Venkata Satya Sai Suresh Santosh Samrat 이름이 부적절합니다