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
让我们编译并运行上述程序,这将产生以下结果 -
打印页面