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 Regular Expression

Java provides support for regular expressions through the java.util.regex package, which includes the Pattern and Matcher classes. Regular expressions are a powerful tool for searching, matching, and manipulating text based on patterns. In this tutorial, we will cover the basics of regular expressions in Java and provide examples of how to use them.

  • Creating a Pattern:

To create a regular expression pattern, you can use the Pattern.compile() method. This method takes a string representing the regular expression pattern and returns a Pattern object.

Example:

import java.util.regex.Pattern;

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

In this example, the pattern \\d+ matches one or more digits.

  • Creating a Matcher:

To match a pattern against a given input string, you can create a Matcher object using the matcher() method of the Pattern class. This method takes the input string as an argument and returns a Matcher object.

Example:

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

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

The Matcher class provides several methods for searching and iterating through matches in the input string:

  • find(): Searches for the next occurrence of the pattern in the input string. Returns true if a match is found, and false otherwise.
  • start(): Returns the start index of the last match found.
  • end(): Returns the end index of the last match found.
  • group(): Returns the matched substring.

Example:

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

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

        while (matcher.find()) {
            System.out.println("Match found at index " + matcher.start() + ": " + matcher.group());
        }
    }
}
  • Replacing matches:

The Matcher class provides methods for replacing matches in the input string:

  • replaceAll(String replacement): Replaces all occurrences of the pattern in the input string with the given replacement string.
  • replaceFirst(String replacement): Replaces the first occurrence of the pattern in the input string with the given replacement string.

Example:

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

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

        String replaced = matcher.replaceAll("***");
        System.out.println("Replaced string: " + replaced);
    }
}
  • Splitting strings:

The Pattern class provides a method for splitting strings based on a regular expression pattern:

  • split(CharSequence input): Splits the input string around matches of the pattern.

Example:

import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String input = "123,abc,456,def";
        Pattern pattern = Pattern.compile(",");
        String[] parts = pattern.split(input);

        for (String part : parts) {
            System.out.println("Part: " + part);
        }
    }
}
  1. Java Pattern and Matcher Classes:

    • The Pattern class is used to compile regular expressions, and the Matcher class is used to match patterns against a given input string.
    String regex = "pattern";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(inputString);
    
  2. Common Regex Patterns in Java:

    • Common regex patterns include literals, character classes, quantifiers, and metacharacters.
    String regex = "\\d{3}-\\d{2}-\\d{4}"; // Social Security Number pattern
    
  3. Matching and Extracting Text in Java with Regex:

    • Use Matcher methods like matches(), find(), and group() to match and extract text.
    if (matcher.matches()) {
        String matchedText = matcher.group();
    }
    
  4. Quantifiers and Character Classes in Java Regex:

    • Quantifiers (*, +, ?, {}) and character classes ([...]) enhance regex flexibility.
    String regex = "[A-Za-z]+"; // Match one or more letters
    
  5. Java Regex Metacharacters and Escape Sequences:

    • Metacharacters like ^, $, ., and escape sequences are used for specific matching.
    String regex = "\\d+\\.\\d+"; // Match decimal numbers
    
  6. Java Regex for Email Validation:

    • Create a regex pattern for email validation.
    String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
    
  7. Validating Numeric Input with Regex in Java:

    • Validate numeric input using regex.
    String numericRegex = "\\d+"; // Match one or more digits
    
  8. Replacing Text with Regex in Java:

    • Use Matcher and String methods for text replacement.
    String replacedText = matcher.replaceAll("replacement");
    
  9. Java Regex Groups and Capturing:

    • Use capturing groups to extract specific parts of the matched text.
    String regex = "(\\d{2})-(\\d{2})-(\\d{4})"; // Date pattern
    
  10. Lookahead and Lookbehind in Java Regex:

    • Lookahead ((?=...)) and lookbehind ((?<=...)) allow you to assert conditions without consuming characters.
    String regex = "\\d+(?=%)"; // Match digits followed by %
    
  11. Java Regex Boundary Matchers:

    • Boundary matchers (\b, \B) help match patterns at word boundaries.
    String regex = "\\bword\\b"; // Match whole word "word"
    
  12. Java Regex and the String Class:

    • The String class has methods like matches(), split(), and replaceAll() for regex operations.
    boolean isMatch = inputString.matches(regex);