Java Regular Expression find repeated occurrences

Introduction

The find() method can search the input sequence for repeated occurrences of the pattern.

Each call to find() picks up where the previous one left off.

For example, the following program finds four occurrences of the pattern "test":

// Use find() to find multiple subsequences. 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
  public static void main(String args[]) {
    Pattern pat = Pattern.compile("test");
    Matcher mat = pat.matcher("test 1 2 3 test test 1 2 3 test ");

    while (mat.find()) {
      System.out.println("test found at index " + mat.start());
    }// w ww. j a  va2s. c  o m
  }
}



PreviousNext

Related