욕심 많은 수량자는 기본 수량자입니다. 욕심 많은 수량자는 입력 문자열에서 최대한 일치합니다(가장 긴 일치). 일치하지 않으면 마지막 문자를 남기고 다시 일치합니다.
reluctant 또는 non-greedy 한정자는 가능한 한 적게 일치하지만 처음에 non-greedy 한정자는 일치가 발생하지 않으면 첫 번째 문자와 일치합니다. 입력 문자열에서 다른 문자를 추가하고 일치를 시도합니다.
"?" greedy 수량사 뒤에는 reluctant 또는 non-greedy quantifier가 됩니다. 다음은 꺼리는 수량사 목록입니다 -
| 한정자 | 설명 |
|---|---|
| 다시*? | 0개 이상의 항목과 일치합니다. |
| 또?? | 0 또는 1회 발생과 일치합니다. |
| 재+? | 하나 이상의 항목과 일치합니다. |
| 다시{n}? | 정확히 n번 일치합니다. |
| 다시{n, }? | 최소 n번 이상 일치합니다. |
| 다시{n, m}? | 적어도 n번에서 최대 m번까지 일치합니다. |
예시
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 = "[0-9]+?";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.print("Pattern found from " + matcher.start()+ " to " + (matcher.end()-1)+"::");
System.out.print(matcher.group());
System.out.println();
}
}
} 출력
Enter input text: 12345678 Pattern found from 0 to 0::1 Pattern found from 1 to 1::2 Pattern found from 2 to 2::3 Pattern found from 3 to 3::4 Pattern found from 4 to 4::5 Pattern found from 5 to 5::6 Pattern found from 6 to 6::7 Pattern found from 7 to 7::8