Quantifiers in Regular Expression

We can use Quntifiers to Specify Number of Occurrences to Match

Expression Meaning
a Exact One ‘a’
a+ At least One ‘a’
a* Any number of a (including 0 no of ‘a’)
a? At most on ‘a’
package demo.example4;

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

/**
 * @author Tyson
 *
 *         Search for number of occurrences in regular expression The group()
 *         method is very important here to see what is matched
 */
public class Demo4 {
	public static void main(String[] args) {
// add \ before\s for space because \ is a escape character
		printMatch("a", "abaabaaab", "Search for Character 'a' only");
		printMatch("a+", "abaabaaab", "Search for single or sequence of 'a' as a single match");
		printMatch("a*", "abaabbaaab", "Search for single or sequence of 'a' or zero 'a' as a single match");
		printMatch("a?", "abaabaaab", "Search for atmost one 'a' or zero 'a' as a single match");
		printMatch("a{2}", "abaabbaaab", "Search for a occured exactly 2 times as a single String");
	}

	public static void printMatch(String regularExpression, String targetString, String comment) {
		Pattern p = Pattern.compile(regularExpression);
		Matcher m = p.matcher(targetString);
		System.out.println("===" + regularExpression + "===in===" + targetString + "=== " + comment);
		while (m.find()) {
			System.out.println(m.start() + "..." + m.group());
		}
		System.out.println("\n");
	}
}

Leave a Comment