This Java tip illustrates an example of a quintessential regular expression search program. Developer may use this code to search for matches in a string by using a regular expression.

  import java.util.regex.*;
    
    public class BasicMatch {
        public static void main(String[] args) {

            // Compile a regular expression
            String patternStr = "b";
            Pattern pattern = Pattern.compile(patternStr);
    
            // Check for the existence of the pattern
            CharSequence inputStr = "a b c b";
            Matcher matcher = pattern.matcher(inputStr);
            boolean matchFound = matcher.find();    // true
    
            // Retrieve matching string
            String match = matcher.group();         // b
    
            // Retrieve 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
        }
    }