如何在 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 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告