Menu
Coddy logo textTech

Regular Expressions Basics

Part of the Logic & Flow section of Coddy's Java journey — lesson 46 of 59.

Regular Expressions (regex) are patterns used to search and validate strings. In Java, we use the matches() method to check if a string matches a pattern.

Check if a string contains only digits:

String text = "12345";
boolean isMatch = text.matches("[0-9]+");

After executing the above code, isMatch contains:

true

Check if a string contains only letters:

String text = "Hello";
boolean isMatch = text.matches("[a-zA-Z]+");

After executing the above code, isMatch contains:

true

challenge icon

Challenge

Easy

Create a method named validateInput that takes two arguments:

  1. A String (text) to validate
  2. A String (type) that specifies the validation type

The method should validate the text based on these types:

  • "number": must contain only digits (0-9)
  • "word": must contain only letters (a-z or A-Z)
  • "email": must contain @ and at least one character before it
  • "phone": must contain exactly 10 digits

Return messages should be:

  • If text is null: return "Invalid input"
  • If type is invalid: return "Invalid type"
  • If validation passes: return "Valid"
  • If validation fails: return "Invalid"

Cheat sheet

Regular Expressions (regex) are patterns used to search and validate strings. In Java, use the matches() method to check if a string matches a pattern.

Check if a string contains only digits:

String text = "12345";
boolean isMatch = text.matches("[0-9]+");

Check if a string contains only letters:

String text = "Hello";
boolean isMatch = text.matches("[a-zA-Z]+");

Common regex patterns:

  • [0-9]+ - one or more digits
  • [a-zA-Z]+ - one or more letters
  • [0-9]{10} - exactly 10 digits
  • .+@.+ - contains @ with at least one character before it

Try it yourself

import java.util.Scanner;

public class Main {
    public static String validateInput(String text, String type) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        String type = scanner.nextLine();
        
        if (text.equals("null")) text = null;
        System.out.println(validateInput(text, type));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow