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.