Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Pattern Class And Matcher Class

In Java, the Pattern class and the Matcher class are part of the java.util.regex package, and they provide support for regular expressions. Regular expressions are used to perform advanced text manipulation, such as searching, extracting, and validating text based on patterns. In this tutorial, we will cover the basics of the Pattern and Matcher classes in Java.

  • Creating a Pattern:

To create a Pattern object, use the static Pattern.compile() method, which takes a regular expression pattern string as its argument.

Example:

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\d+");
    }
}

In this example, we create a Pattern object that matches one or more digits (\\d+).

  • Creating a Matcher:

To create a Matcher object, call the matcher() method on a Pattern object, passing the input string as an argument.

Example:

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

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher("123 abc 456");
    }
}
  • Using the Matcher class:

The Matcher class provides several methods to perform operations on the input string based on the pattern. Some common methods include:

  • find(): Searches for the next occurrence of the pattern in the input string.
  • group(): Returns the matched text.
  • start(): Returns the start index of the matched text.
  • end(): Returns the end index of the matched text.

Example:

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

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher("123 abc 456");

        while (matcher.find()) {
            System.out.println("Matched text: " + matcher.group());
            System.out.println("Start index: " + matcher.start());
            System.out.println("End index: " + matcher.end());
        }
    }
}

Output:

Matched text: 123
Start index: 0
End index: 3
Matched text: 456
Start index: 8
End index: 11
  • Other useful methods:
  • matches(): Returns true if the entire input string matches the pattern, false otherwise.
  • replaceFirst(String replacement): Replaces the first occurrence of the pattern in the input string with the given replacement.
  • replaceAll(String replacement): Replaces all occurrences of the pattern in the input string with the given replacement.

Example:

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

public class Main {
    public static void main(String[] args) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher("123 abc 456");

        System.out.println("Matches: " + matcher.matches());
        System.out.println("Replace first: " + matcher.replaceFirst("XXX"));
        System.out.println("Replace all: " + matcher.replaceAll("XXX"));
    }
}

Output:

Matches: false
Replace first: XXX abc 456
Replace all: XXX abc XXX

In this tutorial, we covered the basics of the Pattern and Matcher classes in Java, which are part of the java.util.regex package. These classes provide powerful functionality for working with regular expressions, enabling you to search, extract, and manipulate text based on patterns.

  1. Java Pattern Class Example Code:

    • The Pattern class compiles regex patterns into a Pattern object for later use with the Matcher.
    import java.util.regex.Pattern;
    
    public class PatternExample {
        public static void main(String[] args) {
            Pattern pattern = Pattern.compile("ab+c");
            // Use the pattern with Matcher...
        }
    }
    
  2. Matching Patterns in Strings using Java:

    • The Matcher class is used to match a Pattern against a given input string.
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class MatcherExample {
        public static void main(String[] args) {
            Pattern pattern = Pattern.compile("ab+c");
            Matcher matcher = pattern.matcher("abbbc");
            boolean isMatch = matcher.matches();
            System.out.println("Is match: " + isMatch);
        }
    }
    
  3. Java Matcher Class Methods and Usage:

    • The Matcher class provides methods like matches(), find(), group(), etc., for working with matches.
    Matcher matcher = pattern.matcher("abbbc");
    if (matcher.find()) {
        String matchedText = matcher.group();
        System.out.println("Matched text: " + matchedText);
    }
    
  4. Pattern.compile() Method in Java:

    • The Pattern.compile() method is used to compile a regular expression pattern into a Pattern object.
    Pattern pattern = Pattern.compile("[0-9]+");
    
  5. Grouping and Capturing in Java Regular Expressions:

    • Parentheses () are used for grouping and capturing parts of a regex pattern.
    Pattern pattern = Pattern.compile("(\\d+)-(\\d+)");
    Matcher matcher = pattern.matcher("123-456");
    if (matcher.find()) {
        String group1 = matcher.group(1);
        String group2 = matcher.group(2);
        System.out.println("Group 1: " + group1 + ", Group 2: " + group2);
    }
    
  6. Java Pattern Flags and Modifiers:

    • Flags and modifiers control aspects like case sensitivity and multiline mode in regular expressions.
    Pattern pattern = Pattern.compile("abc", Pattern.CASE_INSENSITIVE);
    
  7. Matching Multiple Patterns with Java Pattern and Matcher:

    • You can use the | (pipe) operator to match multiple patterns.
    Pattern pattern = Pattern.compile("cat|dog");
    Matcher matcher = pattern.matcher("I have a cat");
    
  8. Java Pattern Split Method:

    • The split() method in Pattern class is used to split a string based on a regex pattern.
    String[] parts = pattern.split("apple,orange,banana");
    
  9. Java Matcher Find Method:

    • The find() method in Matcher class is used to find the next subsequence of the input sequence that matches the pattern.
    while (matcher.find()) {
        // Process each match
    }
    
  10. Java Matcher replaceFirst and replaceAll Methods:

    • The replaceFirst() and replaceAll() methods are used to replace the first or all occurrences of the matched pattern in the input string.
    String replaced = matcher.replaceAll("replacement");
    
  11. Common Regex Patterns and Examples in Java:

    • Common patterns include matching numbers, email addresses, phone numbers, etc. For example, to match an email address:
    Pattern emailPattern = Pattern.compile("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b");