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
학생의 성별을 입력하세요: 남성 Wrong Input