Java如何使用勉强的量词正则表达式?
勉强的量词在输入字符串的开头启动匹配器,然后勉强地一次吃一个字符以寻找匹配项。他们尝试的最后一件事是整个输入字符串。
package org.nhooo.example.regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReluctantQuantifierDemo {
public static void main(String[] args) {
String[] expressions =
{"x??", "x*?", "x+?", "x{2}?", "x{2,}?", "x{2,5}?"};
String input = "xxxxxxx";
for (String expression : expressions) {
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(input);
//查找每个匹配并打印
System.out.println("------------------------------");
System.out.format("regex: %s %n", expression);
while (matcher.find()) {
System.out.format("Text \"%s\" found at %d to %d%n",
matcher.group(), matcher.start(),
matcher.end());
}
}
}
}片段的结果如下所示:
regex: x??
Text "" found at 0 to 0
Text "" found at 1 to 1
Text "" found at 2 to 2
Text "" found at 3 to 3
Text "" found at 4 to 4
Text "" found at 5 to 5
Text "" found at 6 to 6
Text "" found at 7 to 7
------------------------------
regex: x*?
Text "" found at 0 to 0
Text "" found at 1 to 1
Text "" found at 2 to 2
Text "" found at 3 to 3
Text "" found at 4 to 4
Text "" found at 5 to 5
Text "" found at 6 to 6
Text "" found at 7 to 7
------------------------------
regex: x+?
Text "x" found at 0 to 1
Text "x" found at 1 to 2
Text "x" found at 2 to 3
Text "x" found at 3 to 4
Text "x" found at 4 to 5
Text "x" found at 5 to 6
Text "x" found at 6 to 7
------------------------------
regex: x{2}?
Text "xx" found at 0 to 2
Text "xx" found at 2 to 4
Text "xx" found at 4 to 6
------------------------------
regex: x{2,}?
Text "xx" found at 0 to 2
Text "xx" found at 2 to 4
Text "xx" found at 4 to 6
------------------------------
regex: x{2,5}?
Text "xx" found at 0 to 2
Text "xx" found at 2 to 4
Text "xx" found at 4 to 6
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短