勉强量词Java正则表达式
贪婪的量词是默认的量词。贪婪的量词从输入字符串中尽可能匹配(最长匹配),如果未发生匹配,则它离开最后一个字符并再次匹配。
勉强的或非贪婪的量词匹配尽可能少,但如果未发生匹配,则最初的非贪婪的量词将匹配第一个字符,它会从输入字符串中添加另一个字符并尝试进行匹配。
如果您放置“?”在贪婪的量词之后,它变成了勉强的或非贪婪的量词。以下是勉强的量词列表-
示例
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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短