勉强的限定词以尽可能短的字符串大小开头。如果引擎发现匹配项,则该过程将继续查找更多匹配项,否则引擎会向搜索到的字符串部分添加一个字符,然后重试。这一直持续到获得匹配项或字符串用完为止。
正则表达式“ B +?” 用于在字符串“ SkyIsBlue”中查找匹配项。
演示此过程的程序如下:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String args[]) {
String regex = "B+?";
String str = "SkyIsBlue";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while (m.find()) {
System.out.println("Match String starts at index: " + m.start());
}
}
}输出结果
Match String starts at index: 5
现在让我们了解上面的程序。
正则表达式为“ B +?”。在字符串序列“ SkyIsBlue”中搜索。该find()方法用于查找正则表达式是否在输入序列中,并打印其索引。演示此代码段如下:
String regex = "B+?";
String str = "SkyIsBlue";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
while(m.find()) {
System.out.println("Match String starts at index: " + m.start());
}