目录

Matcher usePattern(Pattern newPattern)

描述 (Description)

java.util.regex.Matcher.usePattern(Pattern newPattern)方法更改此Matcher用于查找匹配项的Pattern。

声明 (Declaration)

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

public Matcher usePattern(Pattern newPattern)

参数 (Parameters)

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

返回值 (Return Value)

这个匹配。

异常 (Exceptions)

  • IllegalArgumentException - 如果newPattern为null。

例子 (Example)

以下示例显示了java.util.regex.Matcher.usePattern(Pattern newPattern)方法的用法。

package com.iowiki;
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
↑回到顶部↑
WIKI教程 @2018