Find a word and get offset in text using regex - Java Regular Expressions

Java examples for Regular Expressions:Match

Description

Find a word and get offset in text using regex

Demo Code


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

public class Main {

  private static final String REGEX = "\\bcat\\b";
  private static final String INPUT = "cat cat. cat, cat| cat+ +cat cattie cat";

  public static void main(String args[]) {
    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(INPUT); // get a matcher object
    int count = 0;

    if (m.find()) {
      count++;/*from   ww w. j ava2  s .  c  o m*/
      System.out.println("----------------------------");
      System.out.println("LookingAt:" + m.lookingAt());
      System.out.println("Match number:" + count);
      System.out.println("start(): " + m.start());
      System.out.println("end(): " + m.end());
      System.out.println("Matched:" + m.group());
    }
  }
}

Related Tutorials