Mastering Java Regex Patterns: 10 Powerful Solutions for String Matching and Manipulation

Java Regex Patterns

Below are some common java regex patterns and their outputs.These java regex patterns are designed to test your understanding of regular expressions concept. Preparing for these java regex patterns will help you stand out and showcase your skill during technical interviews.

Java Regex Patterns
Java Regex Patterns

1.Pattern Matching with Regex

import java.util.regex.*;

public class RegexExample {

    public static void main(String[] args) {

        String text = “There are 123 numbers here”;

        // Regular expression to match digits

        String regex = “\\d+”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {

            System.out.println(“Found digits: ” + matcher.group());

        } else {

            System.out.println(“No digits found”);

        }

    }

}

Output:

Found digits: 123

2.Validating Email Address

import java.util.regex.*;

public class EmailValidator {

    public static void main(String[] args) {

        String email = “user@example.com”;

        // Regular expression for validating email

        String regex = “^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(email);

        if (matcher.matches()) {

            System.out.println(“Valid email address”);

        } else {

            System.out.println(“Invalid email address”);

        }

    }

}

Output:

Valid email address

3.Splitting a String Based on a Pattern

import java.util.regex.*;

public class SplitStringExample {

    public static void main(String[] args) {

        String text = “This is an example, of string splitting. Let’s split!”;

        // Regular expression to split by spaces, commas, or periods

        String regex = “[ ,.]”;

        String[] words = text.split(regex);

        System.out.println(“Words after split:”);

        for (String word : words) {

            System.out.println(word);

        }

    }

}

Output:

Words after split:

This

is

an

example

of

string

splitting

Let's

Split

4.Replacing Text using Regex

import java.util.regex.*;

public class ReplaceDigitsExample {

    public static void main(String[] args) {

        String text = “My phone number is 123-456-7890”;

        // Regular expression to match digits

        String regex = “\\d”;

        // Replace all digits with ‘#’

        String replaced = text.replaceAll(regex, “#”);

        System.out.println(“Replaced String: ” + replaced);

    }

}

Output:

Replaced String: My phone number is ###-###-####

5.Extracting a Specific Part of a String

import java.util.regex.*;

public class ExtractDomain {

    public static void main(String[] args) {

        String url = “https://www.example.com/page”;

        // Regular expression to match the domain

        String regex = “https?://(www\\.)?([a-zA-Z0-9-]+)\\.”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {

            System.out.println(“Domain: ” + matcher.group(2));  // group(2) is the domain

        } else {

            System.out.println(“No domain found”);

        }

    }

}

Output:

Domain: example

6.Check if a String Contains a Pattern

import java.util.regex.*;

public class AlphanumericCheck {

    public static void main(String[] args) {

        String input = “Hello123”;

        // Regular expression to match alphanumeric strings

        String regex = “^[a-zA-Z0-9]+$”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(input);

        if (matcher.matches()) {

            System.out.println(“Valid alphanumeric string”);

        } else {

            System.out.println(“Invalid string”);

        }

    }

}

Output:

Valid alphanumeric string

7.Extract Phone Numbers from a Text

import java.util.regex.*;

public class ExtractPhoneNumber {

    public static void main(String[] args) {

        String text = “You can reach me at (123) 456-7890 or at (987) 654-3210.”;

        // Regular expression to match phone numbers in (XXX) XXX-XXXX format

        String regex = “\\(\\d{3}\\) \\d{3}-\\d{4}”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(text);

        while (matcher.find()) {

            System.out.println(“Found phone number: ” + matcher.group());

        }

    }

}

Output:

Found phone number: (123) 456-7890

Found phone number: (987) 654-3210

8.Validate a Strong Password

import java.util.regex.*;

public class PasswordValidator {

    public static void main(String[] args) {

        String password = “StrongP@ssw0rd”;

        // Regular expression for a strong password

        String regex = “^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(password);

        if (matcher.matches()) {

            System.out.println(“Valid strong password.”);

        } else {

            System.out.println(“Invalid password.”);

        }

    }

}

Output:

Valid strong password.

9.Replace Multiple Spaces with a Single Space

import java.util.regex.*;

public class ReplaceMultipleSpaces {

    public static void main(String[] args) {

        String text = “This   is   a  string   with    multiple spaces.”;

        // Regular expression to match multiple spaces

        String regex = “\\s+”;

        // Replace multiple spaces with a single space

        String result = text.replaceAll(regex, ” “);

        System.out.println(“Result: ” + result);

    }

}

Output:

Result: This is a string with multiple spaces.

10.Extract Date from a String

import java.util.regex.*;

public class ExtractDate {

    public static void main(String[] args) {

        String text = “The meeting is scheduled for 05/12/2024 at 10 AM.”;

        // Regular expression to match dates in MM/DD/YYYY format

        String regex = “(\\d{2}/\\d{2}/\\d{4})”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(text);

        if (matcher.find()) {

            System.out.println(“Found date: ” + matcher.group());

        } else {

            System.out.println(“No date found.”);

        }

    }

}

Output:

Found date: 05/12/2024

11.Validate a Date in YYYY-MM-DD Format

import java.util.regex.*;

public class DateValidator {

    public static void main(String[] args) {

        String date = “2023-02-28”; // Test with different date inputs

        // Regular expression to match a date in YYYY-MM-DD format

        String regex = “^(?:19|20)\\d\\d-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$”;

        Pattern pattern = Pattern.compile(regex);

        Matcher matcher = pattern.matcher(date);

        if (matcher.matches()) {

            System.out.println(“Valid Date”);

        } else {

            System.out.println(“Invalid Date”);

        }

    }

}

Output:

Valid Date

 

 

Leave a Comment