贪婪限定符 Java 正则表达式中的 java。
贪婪限定符是默认限定符。当匹配未发生时,贪婪限定符将尽可能多地匹配输入字符串(尽可能最长的匹配),它会跳过最后一个字符并再次匹配。以下是贪婪限定符的列表 -
| 限定符 | 说明 |
|---|---|
| re* | 匹配零次或多次出现。 |
| re? | 匹配零次或一次出现。 |
| re+ | 匹配一次或多次出现。 |
| re{n} | 精确匹配 n 次出现。 |
| re{n, } | 至少匹配 n 次。 |
| re{n, m} | 至少匹配 n 次,最多匹配 m 次。 |
示例
在以下 Java 示例中,我们尝试匹配 1 个或多个数字,我们的输入字符串为 45545,虽然值 4、45、455 等符合条件,但我们正在使用贪婪限定符,它匹配最长可能。
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);
System.out.println(“”Matched text: );
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}输出
Enter input text: Matched text: 45545
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP