Regular Expression Search Program Template - Java Regular Expressions

Java examples for Regular Expressions:Match

Description

Regular Expression Search Program Template

Demo Code

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

public class Main {
  public static void main(String[] args) {
    // Compile regular expression
    String patternStr = "b";
    Pattern pattern = Pattern.compile(patternStr);

    // Determine if pattern exists in input
    CharSequence inputStr = "a b c b";
    Matcher matcher = pattern.matcher(inputStr);
    boolean matchFound = matcher.find(); 
    System.out.println(matchFound);

    // Get matching string
    String match = matcher.group(); // b
    System.out.println(match);//  w w w .j  av  a 2s.com

    // Get indices of matching string
    int start = matcher.start(); // 2
    System.out.println(start);
    int end = matcher.end(); // 3
    System.out.println(end);
    // the end is index of the last matching character + 1

    // Find the next occurrence
    matchFound = matcher.find(); // true
    System.out.println(matchFound);
  }
}

Result


Related Tutorials