第二百零四节 Java正则表达式教程 - Java正则表达式量词

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);
  }
}

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

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值