您的位置 首页 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);
 }
}
 

上面的代码生成以下结果。

文章来源:智云一二三科技

文章标题:Java正则表达式-量词

文章地址:https://www.zhihuclub.com/185633.shtml

关于作者: 智云科技

热门文章

发表回复

您的电子邮箱地址不会被公开。

网站地图