Basic Matching with Regular Expressions


For the best introduction see my article on Regular Expressions . This example shows a random set of examples in Java.

import java.util.regex.*;

public class  {
    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();    // true

        // Get matching string
        String match =;         // b

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

        // Find the next occurrence
        matchFound = matcher.find();            // true


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.