在 Java 中使用 find() 來查詢多個子序列


find() 方法在輸入序列中查詢與所需模式匹配的多個子序列。該方法可在 Matcher 類中找到,而 Matcher 類可在 java.util.regex 包中找到

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

示例

 線上演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("the");
      Matcher m = p.matcher("eclipses of the sun and the moon");
      System.out.println("Subsequence: the");
      System.out.println("Sequence: eclipses of the sun and the moon");
      System.out.println();
      while (m.find()) {
         System.out.println("the found at index " + m.start());
      }
   }
}

輸出

Subsequence: the
Sequence: eclipses of the sun and the moon
the found at index 12
the found at index 24

現在,讓我們來了解一下上面的程式。

在字串序列“eclipses of the sun and the moon”中搜索子序列“the”。然後使用 find() 方法來查詢子序列在輸入序列中出現的次數,然後列印所需結果。演示這一過程的程式碼片段如下

Pattern p = Pattern.compile("the");
Matcher m = p.matcher("eclipses of the sun and the moon");
System.out.println("Subsequence: the" );
System.out.println("Sequence: eclipses of the sun and the moon" );
System.out.println();
while (m.find()) {
   System.out.println("the found at index " + m.start());
}

更新時間: 30-07-2019

105 次瀏覽

啟動你的 職業生涯

完成課程可獲得認證

開始
廣告
© . All rights reserved.