Explain Regular Expression in Java with example

Regular Expression in Java

Regular Expression in Java – A Regular Expression (regex or regexp) in Java is a sequence of characters that forms a search pattern. This pattern can be used for string searching and manipulation. Regular expressions are extremely useful for text processing tasks such as validation, parsing, and string matching.

In Java, the java.util.regex package provides classes for working with regular expressions. The two main classes are Pattern and Matcher.

  • Pattern: A compiled representation of a regular expression.
  • Matcher: An engine that performs match operations on a character sequence by interpreting a Pattern.

Here’s an example to illustrate the usage of regular expressions in Java:

Example: Validating an Email Address using Regular Expression in Java

Let’s write a Java program to validate if a given string is a valid email address.

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

public class RegexExample {
    public static void main(String[] args) {
        // Define the regular expression for an email address
        String emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
        
        // Compile the regular expression into a Pattern object
        Pattern pattern = Pattern.compile(emailRegex);
        
        // Example email addresses
        String[] emails = {
            "test@example.com",
            "invalid-email",
            "user.name@domain.com",
            "user@domain.co.in",
            "user@domain"
        };
        
        for (String email : emails) {
            // Create a Matcher object
            Matcher matcher = pattern.matcher(email);
            
            // Check if the email matches the pattern
            if (matcher.matches()) {
                System.out.println(email + " is a valid email address.");
            } else {
                System.out.println(email + " is not a valid email address.");
            }
        }
    }
}

Explanation:

  • Regular Expression Definition:
    • ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$
      • ^: Start of the line
      • [a-zA-Z0-9._%+-]+: One or more alphanumeric characters, dots, underscores, percent signs, plus signs, or hyphens
      • @: At symbol
      • [a-zA-Z0-9.-]+: One or more alphanumeric characters, dots, or hyphens
      • \\.: Literal dot
      • [a-zA-Z]{2,6}: Two to six alphabetic characters (for the domain extension)
      • $: End of the line
  • Compiling the Regular Expression:
    • Pattern pattern = Pattern.compile(emailRegex); compiles the regular expression into a pattern that can be used for matching.
  • Matching the Pattern:
    • Matcher matcher = pattern.matcher(email); creates a matcher that will match the given email against the pattern.
    • matcher.matches() checks if the entire string matches the pattern.
  • Output:
    • The program checks each email in the array and prints whether it is valid or not according to the regular expression.

This is a basic example of using regular expressions in Java. Regular expressions can be much more complex and powerful, depending on the requirements of the text processing task.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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