Regular Expression Exercises

Match lowercase String

Match a string that consists only of lowercase letters (a to z)

Show answer:
"hello".matches("[a-z]+");  // true
"Hello".matches("[a-z]+");  // false

Match digits

Match a string that consists only of digits (0-9).

Show answer:
"12345".matches("\\d+");  // true
"abc123".matches("\\d+");  // false

Starts with A

Check if the string starts with the letter “A”.

Show answer:
"Apple".matches("^A.*");  // true
"banana".matches("^A.*");  // false

Has a digit

Check if the string contains a digit.

Show answer:
"hello123".matches(".*\\d.*");  // true
"hello".matches(".*\\d.*");  // false

Four digits

Match a string of exactly 4 digits.

Show answer:
"1234".matches("\\d{4}");  // true
"12345".matches("\\d{4}");  // false

Only alphabetic characters allowed

Match a string containing only alphabetic characters (uppercase and lowercase).

Show answer:
"Hello".matches("[a-zA-Z]+");  // true
"Hello123".matches("[a-zA-Z]+");  // false

Three letters, three digits

Match a string with 3 letters followed by 3 digits (e.g., “abc123”).

Show answer:
"abc123".matches("[a-zA-Z]{3}\\d{3}");  // true
"ab123".matches("[a-zA-Z]{3}\\d{3}");  // false

Only alphanumeric characters allowed

Match a string containing only alphanumeric characters (letters, digits, and underscores).

Show answer:
"abc123_".matches("\\w+");  // true
"abc 123".matches("\\w+");  // false

Match a phone number

Match a phone number in the format XXX-XXX-XXXX (e.g., 123-456-7890).

Show answer:
"123-456-7890".matches("\\d{3}-\\d{3}-\\d{4}");  // true
"123-4567-890".matches("\\d{3}-\\d{3}-\\d{4}");  // false

One uppercase, one lowercase, one digit

Match a string that contains at least one uppercase letter, one lowercase letter, and one digit

Show answer:
"A1b".matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).+$");  // true
"abc123".matches("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).+$");  // false


Leave a Reply

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

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories