不情愿量词 Java 正则表达式
贪婪量词是默认的量词。在输入字符串中,贪婪量词尽可能地匹配(最长的匹配),如果未匹配,则跳过最后一个字符并再次匹配。
而不情愿或非贪婪量词尽可能少的匹配,最初,非贪婪量词匹配第一个字符,如果未匹配,则从输入字符串中添加另一个字符并尝试匹配。
如果在贪婪量词后面加上 “?”,它将变为不情愿或非贪婪量词。以下是所列不情愿量词列表 -
| 量词 | 说明 |
|---|---|
| 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]+?";
//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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP