我們可以指定正則表達(dá)式中的字符的次數(shù)可以匹配字符序列。
為了使用正則表達(dá)式表達(dá)一個(gè)數(shù)字或更多的模式,我們可以使用量詞。
下表列出了量詞及其含義。
量詞 | 含義 |
---|---|
* | 零次或更多次 |
+ | 一次或多次 |
? | 一次或根本不 |
{m} | 正好m次 |
{m,} | 至少m次 |
{m,n} | 至少m,但不超過n次 |
量詞必須遵循字符或字符類。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { // A group of 3 digits followed by 7 digits. String regex = "\\b(\\d{3})\\d{7}\\b"; // Compile the regular expression Pattern p = Pattern.compile(regex); String source = "12345678, 12345, and 9876543210"; // Get the Matcher object Matcher m = p.matcher(source); // Start matching and display the found area codes while (m.find()) { String phone = m.group(); String areaCode = m.group(1); System.out.println("Phone: " + phone + ", Area Code: " + areaCode); } } }
上面的代碼生成以下結(jié)果。
*
匹配零個(gè)或多個(gè) d
。
import java.util.regex.Pattern; public class Main { public static void main(String args[]) { String regex = "ad*"; String input = "add"; boolean isMatch = Pattern.matches(regex, input); System.out.println(isMatch); } }
上面的代碼生成以下結(jié)果。
更多建議: