Matcher.find(int) 方法在 Java 正則表示式中的作用


Matcher.find(int) 方法在輸入序列中找到引數指定的子序列編號之後的子序列,此方法在 java.util.regex 包中提供的 Matcher 類中提供。

Matcher.find(int) 方法有一個引數,即獲得子序列的子序列編號,如果獲得所需子序列,則返回真,否則返回假。

一個在 Java 正則表示式中演示 Matcher.find(int) 方法的程式如下 −

示例

 線上演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
   public static void main(String args[]) {
      Pattern p = Pattern.compile("apple", Pattern.CASE_INSENSITIVE);
      Matcher m = p.matcher("apple APPLE Apple aPPLE");
      System.out.println("apple APPLE Apple aPPLE");
      m.find(6);
      System.out.println(m.group());
      System.out.println("
apple APPLE Apple aPPLE");       m.find(12);       System.out.println(m.group());       System.out.println("
apple APPLE Apple aPPLE");       m.find(0);       System.out.println(m.group());    } }

以上程式輸出如下 −

apple APPLE Apple aPPLE
APPLE
apple APPLE Apple aPPLE
Apple
apple APPLE Apple aPPLE
apple

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

使用 find(int) 方法找到輸入序列“apple APPLE Apple aPPLE”中子序列編號為 6、12 和 0 之後的子序列,並列印所需的輸出,如下面的程式碼片段所示 −

Pattern p = Pattern.compile("apple", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("apple APPLE Apple aPPLE");
System.out.println("apple APPLE Apple aPPLE");
m.find(6);
System.out.println(m.group());
System.out.println("
apple APPLE Apple aPPLE"); m.find(12); System.out.println(m.group()); System.out.println("
apple APPLE Apple aPPLE"); m.find(0); System.out.println(m.group());

更新時間:30-6-2020

210 次瀏覽

開啟你的 職業 生涯

完成課程並獲得認證

開始
Advertisements