java.util.regex.Matcher.usePattern()方法



描述

java.util.regex.Matcher.usePattern(Pattern newPattern) 方法更改此 Matcher 用於查詢匹配項的模式。

宣告

以下是 java.util.regex.Matcher.usePattern(Pattern newPattern) 方法的宣告。

public Matcher usePattern(Pattern newPattern)

public Matcher usePattern(Pattern newPattern)

  • 引數

newPattern - 此匹配器使用的新的模式。

返回值

此匹配器。

  • 異常

IllegalArgumentException - 如果 newPattern 為 null。

示例

package com.tutorialspoint;

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

public class MatcherDemo {
   private static String REGEX = "(a*b)(foo)";
   private static String INPUT = "aabfooaabfooabfoob";

   public static void main(String[] args) {
      // create a pattern
      Pattern pattern = Pattern.compile(REGEX);
      
      // get a matcher object
      Matcher matcher = pattern.matcher(INPUT); 
      
      while(matcher.find()) {
         //Prints the start index of the subsequence captured by the given group.
         System.out.println("Second Capturing Group, (foo) Match String start(): "+matcher.start(1));
      }  
      matcher.reset();
      matcher.usePattern(Pattern.compile("(a*b)(foob)"));
      
      while(matcher.find()) {
         //Prints the start index of the subsequence captured by the given group.
         System.out.println("Second Capturing Group, (fooab) Match String start(): "+matcher.start(1));
      }  
   }
}

現場演示

Second Capturing Group, (foo) Match String start(): 0
Second Capturing Group, (foo) Match String start(): 6
Second Capturing Group, (foo) Match String start(): 12
Second Capturing Group, (fooab) Match String start(): 12
讓我們編譯並執行上述程式,這將產生以下結果 -
列印頁面
© . All rights reserved.