Java 正则表达式中 reluctant 限定符


reluctant 限定符以可能的最短字符串大小开头。如果引擎找到匹配项,则进程继续查找更多匹配项,否则引擎会向所搜索的字符串部分添加一个字符并再次尝试。这将一直持续下去,直到获得匹配项或用尽字符串为止。

正则表达式“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());
}

更新时间: 2019 年 7 月 30 日

135 次浏览

Kickstart Your Career

完成课程认证

开始
广告
© . All rights reserved.