使用量词在 Java 中查找匹配


其中一个量词是加号 (+)。它匹配序列中指定的一个或多个子序列。

下文给出了一个演示使用量词加号 (+) 在 Java 中查找匹配的程序

示例

 实时演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("o+");
      Matcher m = p.matcher("o oo ooo");
      System.out.println("The input string is: o oo ooo");
      System.out.println("The Regex is: o+ ");
      System.out.println();
      while (m.find()) {
         System.out.println("Match: " + m.group());
      }
   }
}

输出

The input string is: o oo ooo
The Regex is: o+
Match: o
Match: oo
Match: ooo

现在让我们来理解一下上面的程序。

在字符串序列 "o oo ooo" 中搜索子序列 “o+”。然后使用 find() 方法查找子序列(即 o 后跟任意数量的 o)是否在输入序列中,并打印所需结果。演示此过程的代码片段如下

Pattern p = Pattern.compile("o+");
Matcher m = p.matcher("o oo ooo");
System.out.println("The input string is: o oo ooo");
System.out.println("The Regex is: o+ ");
System.out.println();
while (m.find()) {
   System.out.println("Match: " + m.group());
}

更新于: 2019 年 7 月 30 日

已浏览 72 次

开启你的 职业 生涯

完成课程后获得认证

开始
广告
© . All rights reserved.