不情愿量词 Java 正则表达式

javaobject oriented programmingprogramming更新于 2025/2/12 4:28:17

贪婪量词是默认量词。贪婪量词会尽可能多地匹配输入字符串(尽可能长的匹配),如果没有匹配,它会保留最后一个字符并再次匹配。

而不情愿或非贪婪量词会尽可能少地匹配,最初非贪婪量词匹配第一个字符,如果没有匹配,它会从输入字符串中添加另一个字符并尝试匹配。

如果在贪婪量词后放置"?",它就会变成不情愿或非贪婪量词。以下是勉强量词 −

的列表
量词描述
re*?匹配零次或多次。
re??匹配零次或 1 次。
re+?匹配一次或多次。
re{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 = 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

相关文章


有用资源