Regular Expressions in Java


Introduction

A Regular Expression (regex) is a sequence of characters defining a search pattern. In Java, the java.util.regex package provides classes for working with regex patterns and matching operations.

Core Classes in java.util.regex

  • Pattern: Represents the compiled regex pattern.
  • Matcher: Performs match operations on a character sequence using the pattern.

1. Basic Usage

Example: Matching a Pattern

    import java.util.regex.*;
    
    public class RegexExample {
        public static void main(String[] args) {
            // Compile the regex pattern
            Pattern pattern = Pattern.compile("hello");
    
            // Create a matcher for the input string
            Matcher matcher = pattern.matcher("hello world");
    
            // Check if the pattern matches
            if (matcher.find()) {
                System.out.println("Pattern found!");
            } else {
                System.out.println("Pattern not found.");
            }
        }
    }
        

2. Common Regex Patterns

  • \d: Matches a digit (0-9).
  • \D: Matches a non-digit.
  • \w: Matches a word character (a-z, A-Z, 0-9, _).
  • \W: Matches a non-word character.
  • \s: Matches a whitespace character.
  • \S: Matches a non-whitespace character.
  • .*: Matches zero or more of any character.

3. Advanced Operations

Example: Extracting Substrings

    import java.util.regex.*;
    
    public class RegexExtractExample {
        public static void main(String[] args) {
            String input = "Order123: Shipped";
    
            // Define a pattern to extract order number
            Pattern pattern = Pattern.compile("Order(\\d+)");
            Matcher matcher = pattern.matcher(input);
    
            if (matcher.find()) {
                System.out.println("Order Number: " + matcher.group(1));
            }
        }
    }
        

Example: Validating Input

    import java.util.regex.*;
    
    public class RegexValidationExample {
        public static void main(String[] args) {
            String email = "example@domain.com";
    
            // Email regex pattern
            String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
            boolean isValid = Pattern.matches(regex, email);
    
            System.out.println("Is the email valid? " + isValid);
        }
    }
        

4. Splitting Strings

You can use regex to split strings efficiently.

Example: Splitting by Delimiters

    public class RegexSplitExample {
        public static void main(String[] args) {
            String input = "apple,orange,banana";
    
            // Split the string by commas
            String[] fruits = input.split(",");
    
            for (String fruit : fruits) {
                System.out.println(fruit);
            }
        }
    }
        

Conclusion

Regular expressions are powerful tools for pattern matching and text processing in Java. With classes like Pattern and Matcher, you can perform complex operations like validation, searching, and splitting strings effectively.





Advertisement