Java正则表达式教程 - Java正则表达式量词
我们可以指定正则表达式中的字符的次数可以匹配字符序列。
为了使用正则表达式表达一个数字或更多的模式,我们可以使用量词。
下表列出了量词及其含义。
| 量词 | 含义 |
|---|---|
| * | 零次或更多次 |
| + | 一次或多次 |
| ? | 一次或根本不 |
| {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);
}
}
}
上面的代码生成以下结果。
![]()
例2
* 匹配零个或多个 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);
}
}
上面的代码生成以下结果。
![]()








![[机器学习]--线性回归算法](https://i-blog.csdnimg.cn/direct/38189eeaa18b44b282fedae6a3463eea.png)


![自开发多功能Vue组件:可定义滚动速度[回到顶部/底部]图标组件的安装与使用!](https://i-blog.csdnimg.cn/direct/541bdb7a523748a4bda4c1dc83d9b3ed.jpeg#pic_center)







