如何在 Java 正则表达式中找到符合所需模式的输入序列中的子序列?


find() 方法找到与所需模式匹配的输入序列中的子序列。该方法在 Matcher 类中可用,Matcher 类在 java.util.regex 程序包中可用。

下面提供了一个在 Java 正则表达式中演示方法 Matcher.find() 的程序。

示例

 在线演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("Sun");
      Matcher m = p.matcher("The Earth revolves around the Sun");
      System.out.println("Subsequence: Sun");
      System.out.println("Sequence: The Earth revolves around the Sun");
      if (m.find())
         System.out.println("
Subsequence found");       else          System.out.println("
Subsequence not found");    } }

输出

Subsequence: Sun
Sequence: The Earth revolves around the Sun
Subsequence found

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

在字符串序列“地球绕着太阳转”中搜索子序列“太阳”。然后使用 find() 方法查找子序列是否在输入序列中,并打印所需结果。演示此内容的代码片段如下所示:

Pattern p = Pattern.compile("Sun");
Matcher m = p.matcher("The Earth revolves around the Sun");
System.out.println("Subsequence: Sun" );
System.out.println("Sequence: The Earth revolves around the Sun" );
if (m.find())
   System.out.println("
Subsequence found"); else    System.out.println("
Subsequence not found");

更新于:2019 年 7 月 30 日

408 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.