使用 find() 在 Java 正則表示式中查詢子序列


find() 方法在輸入序列中查詢與所需模式匹配的子序列。此方法在 java.util.regex 包中 Matcher 類中提供。

下面的程式使用了 find() 方法在 Java 中查詢子序列

示例

 線上演示版本

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

輸出

Subsequence: cool
Sequence: Java is cool
Subsequence found

現在讓我們瞭解一下上面的程式。

在字串序列“Java is cool”中搜索子序列“cool”。然後,使用 find() 方法查詢輸入序列中是否有該子序列,並列印所需的結果。如下面的程式碼片段所示:

Pattern p = Pattern.compile("cool");
Matcher m = p.matcher("Java is cool");
System.out.println("Subsequence: cool" );
System.out.println("Sequence: Java is cool" );
if (m.find())
   System.out.println("
Subsequence found"); else    System.out.println("
Subsequence not found");

更新於:2019 年 7 月 30 日

60 次瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.