하위 표현식/메타 문자 "( )"는 정규 표현식을 그룹화하고 일치하는 텍스트를 기억합니다.
예시 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main( String args[] ) { String input = "Hello how are you welcome to Tutorialspoint"; String regex = "H(ell|ow)"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } }
출력
Match found
예시 2
다음 예에서는 숫자가 포함된 문장을 일치시키려고 합니다. −
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PatternExample { public static void main(String[] args) { System.out.println("Enter input string: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //Regular expression using groups String regex = "(?:.*)(\\d+)(.*)"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(input); boolean bool = matcher.matches(); if(bool) { System.out.println("Match found"); } else { System.out.println("Match not found"); } } }
출력
Enter input string: This is a 5363 test string Match found