贪婪的量词是默认的量词。贪婪的量词从输入字符串中尽可能匹配(最长匹配),如果未发生匹配,则它离开最后一个字符并再次匹配。
勉强的或非贪婪的量词匹配尽可能少,但如果未发生匹配,则最初的非贪婪的量词将匹配第一个字符,它会从输入字符串中添加另一个字符并尝试进行匹配。
如果您放置“?” 在贪婪的量词之后,它变成了勉强的或非贪婪的量词。以下是勉强的量词列表-
| 量词 | 描述 | 
|---|---|
| 回覆*? | 匹配零个或多个事件。 | 
| 回覆?? | 匹配零个或1匹配项。 | 
| 重新+? | 匹配一个或多个事件。 | 
| 重新{n}? | 精确匹配n次出现。 | 
| re {n,}? | 至少匹配n个事件。 | 
| re {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]+?";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的已编译模式
      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