Java 정규식은 다음과 같은 3가지 논리 연산자를 지원합니다. -
-
XY:X 다음에 Y
-
X|Y:X 또는 Y
-
(X):캡처 그룹.
XY:X 다음에 Y
이것은 단순히 두 개의 단일 연속 문자와 일치합니다.
예시
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "am";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
} 출력 1
Enter input text: sample text Match occurred
출력 2
Enter input text: hello how are you Match not occurred
X|Y
이것은 "|"를 둘러싼 두 개의 표현식/문자 중 하나와 일치합니다.
예시
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 Tutorialspoint";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
} 출력
Number of matches: 2
(X):캡처 그룹
캡처 그룹을 사용하면 여러 문자를 단일 단위로 취급할 수 있습니다. 이러한 문자를 괄호 안에 넣으면 됩니다.
예시
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CapturingGroups {
public static void main( String args[] ) {
System.out.println("Enter input text");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "(.*)(\\d+)(.*)";
//Create a Pattern object
Pattern pattern = Pattern.compile(regex);
//Now create matcher object.
Matcher matcher = pattern.matcher(input);
if (matcher.find( )) {
System.out.println("Found value: " + matcher.group(0) );
System.out.println("Found value: " + matcher.group(1) );
System.out.println("Found value: " + matcher.group(2) );
System.out.println("Found value: " + matcher.group(3) );
} else {
System.out.println("NO MATCH");
}
}
} 출력
Enter input text sample data with 1234 (digits) in middle Found value: sample data with 1234 (digits) in middle Found value: sample data with 123 Found value: 4 Found value: (digits) in middle