Java Program to find two letter capital words using Regex

Java Program to find two letter capital words using Regex

Java Program to find two letter capital words in Java using Regex:

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

public class RegexAppealAddress {
	public static void main(String[] args) {
		String input = "Javadomain is also called as JD which contains JAVA tutorials and programmings";
		// This prints JD and JA
		// Pattern regexPattern = Pattern.compile("\\s[A-Z]{2,2}");
		// This prints only JD
		Pattern regexPattern = Pattern.compile("\\s[A-Z]{2,2}\\s");
		Matcher matcher = regexPattern.matcher(input);
		while (matcher.find()) {
			System.out.println(matcher.group());
		}
	}
}

Output:

 JD 

Explanation:

1. \\s for whitespaces
2. [A-Z] for only capital letters
3. {2,2} for minimum two letters and maximum two letters.

Java Recommended Books:

483 total views, 3 views today

Leave a Reply

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