在 Java 正則表示式中使用 ? 量詞
總體而言,量詞 ? 表示指定模式出現 0 次或 1 次。例如,X? 表示 X 出現 0 次或 1 次。
正則表示式 “t.+?m” 用來使用量詞 ? 在字串 “tom and tim are best friends” 中查詢匹配。
演示此示例的程式如下所示
示例
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String args[]) { Pattern p = Pattern.compile("t.+?m"); Matcher m = p.matcher("tom and tim are best friends"); System.out.println("The input string is: tom and tim are best friends"); System.out.println("The Regex is: t.+?m"); System.out.println(); while (m.find()) { System.out.println("Match: " + m.group()); } } }
輸出
The input string is: tom and tim are best friends The Regex is: t.+?m Match: tom Match: tim
現在讓我們瞭解一下上述程式。
在字串序列 "tom and tim are best friends" 中搜索子序列 “t.+?m”。find() 方法用於查詢子序列,即以 t 開頭、後面以任意數量 t 結尾且以 m 結尾的子序列是否在輸入序列中,然後列印所需結果。
廣告