Open In App

Regular Expressions in Java

Last Updated : 21 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Regular Expressions or Regex (in short) in Java is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are a few areas of strings where Regex is widely used to define the constraints. Regular Expressions in Java are provided under java.util.regex package. This consists of 3 classes and 1 interface. The java.util.regex package primarily consists of the following three classes as depicted below in tabular format as follows:

Regex Classes and Interfaces

Regex in Java provides 3 classes and 1 interface which are as follows:

  1. Pattern Class
  2. Matcher Class
  3. PatternSyntaxException Class
  4. MatchResult Interface

More understanding can be interpreted from the image provided below as follows:

Java Regex

S. No. Class/Interface Description
1. Pattern Class Used for defining patterns
2. Matcher Class Used for performing match operations on text using patterns
3. PatternSyntaxException Class Used for indicating syntax error in a regular expression pattern
4. MatchResult Interface Used for representing the result of a match operation

Pattern Class

This class is a compilation of regular expressions that can be used to define various types of patterns, providing no public constructors. This can be created by invoking the compile() method which accepts a regular expression as the first argument, thus returning a pattern after execution.

S. No.  Method Description
1. compile(String regex) It is used to compile the given regular expression into a pattern.
2. compile(String regex, int flags) It is used to compile the given regular expression into a pattern with the given flags.
3. flags() It is used to return this pattern’s match flags.
4. matcher(CharSequence input) It is used to create a matcher that will match the given input against this pattern.
5. matches(String regex, CharSequence input) It is used to compile the given regular expression and attempts to match the given input against it.
6. pattern() It is used to return the regular expression from which this pattern was compiled.
7. quote(String s) It is used to return a literal pattern String for the specified String.
8. split(CharSequence input) It is used to split the given input sequence around matches of this pattern.
9. split(CharSequence input, int limit) It is used to split the given input sequence around matches of this pattern. The limit parameter controls the number of times the pattern is applied.
10. toString() It is used to return the string representation of this pattern.

Example: Pattern class 

Java




// Java Program Demonstrating Working of matches() Method
// Pattern class
 
// Importing Pattern class from java.util.regex package
import java.util.regex.Pattern;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Following line prints "true" because the whole
        // text "geeksforgeeks" matches pattern
        // "geeksforge*ks"
        System.out.println(Pattern.matches(
            "geeksforge*ks", "geeksforgeeks"));
 
        // Following line prints "false" because the whole
        // text "geeksfor" doesn't match pattern "g*geeks*"
        System.out.println(
            Pattern.matches("g*geeks*", "geeksfor"));
    }
}


Output

true
false

Matcher class

This object is used to perform match operations for an input string in Java, thus interpreting the previously explained patterns. This too defines no public constructors. This can be implemented by invoking a matcher() on any pattern object.

S. No. Method Description
1. find() It is mainly used for searching multiple occurrences of the regular expressions in the text.
2. find(int start) It is used for searching occurrences of the regular expressions in the text starting from the given index.
3. start() It is used for getting the start index of a match that is being found using find() method.
4. end() It is used for getting the end index of a match that is being found using find() method. It returns the index of the character next to the last matching character.
5. groupCount()     It is used to find the total number of the matched subsequence.
6. group() It is used to find the matched subsequence.
7. matches() It is used to test whether the regular expression matches the pattern.

Note: T Pattern.matches() checks if the whole text matches with a pattern or not. Other methods (demonstrated below) are mainly used to find multiple occurrences of patterns in the text.

Let us do discuss a few sample programs as we did for the Pattern class. Here we will be discussing a few Java programs that demonstrate the workings of compile(), find(), start(), end(), and split() in order to get a better understanding of the Matcher class.

Example 1: Pattern Searching 

Java




// Java program to demonstrate working of
// String matching in Java
 
// Importing Matcher and Pattern class
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Create a pattern to be searched
        // Custom pattern
        Pattern pattern = Pattern.compile("geeks");
 
        // Search above pattern in "geeksforgeeks.org"
        Matcher m = pattern.matcher("geeksforgeeks.org");
 
        // Finding string using find() method
        while (m.find())
 
            // Print starting and ending indexes
            // of the pattern in the text
            // using this functionality of this class
            System.out.println("Pattern found from "
                               + m.start() + " to "
                               + (m.end() - 1));
    }
}


Output

Pattern found from 0 to 4
Pattern found from 8 to 12

Regex Character classes

                    Character Class                    

Description

[xyz]

x,y or z

[^xyz]

Any characters other than x,y or z

[a-zA-Z]

characters from range a to z or A to Z.

[a-f[m-t]]

Union of a to f and m to t.

[a-z && p-y] 

All the range of elements intersection between two ranges 

[a-z && [^bc]]

a to z union with except b and c

[a-z && [^m-p]]

a to z union with except range m to p

Below is the implementation of the above topic:

Java




// Java Program to check on Regex
import java.io.*;
import java.util.regex.*;
 
// Driver class
class GFG {
    // Main function
    public static void main(String[] args)
    {
        // Checks if the string matches with the regex
        // Should be single character a to z
        System.out.println(Pattern.matches("[a-z]", "g"));
 
        // Check if the element is range a to z or A to Z
        System.out.println(
            Pattern.matches("[a-zA-Z]", "Gfg"));
    }
}


Output

true
false

Regex Metacharacters

                    Regex                     

Description

X?

X appears once or not

X+

X appears once or more than once

X*

X appears zero or not once

X{n}

X appears n times

X{n,}

X appears n times or more than n

X{n,m}

X appears greater than equal to n times and less than m times.

Below is the implementation of Regex Metacharacters:

Java




// Java Program to check on regex
import java.io.*;
import java.util.regex.*;
 
// Driver class
class GFG {
    // Main function
    public static void main(String[] args)
    {
        // Checking all the strings using regex
        System.out.println(Pattern.matches("[b-z]?", "a"));
 
        // Check if all the elements are in range a to z
        // or A to Z
        System.out.println(
            Pattern.matches("[a-zA-Z]+", "GfgTestCase"));
 
        // Check if elements is not in range a to z
        System.out.println(Pattern.matches("[^a-z]?", "g"));
 
        // Check if all the elements are either g,e,k or s
        System.out.println(
            Pattern.matches("[geks]*", "geeksgeeks"));
    }
}


Output

false
true
false
true

Java Regex Finder Example

                    Regex                  

                                       Description                                        

.

Any character

\d

Any digits, [0-9]

\D

Any non-digit, [^0-9]

\s

Whitespace character, [\t\n\x0B\f\r]

\S

Non-whitespace character, [^\s]

\w

Word character, [a-zA-Z_0-9]

\W

Non-word character, [^\w]

\b

Word boundary

\B

Non -Word boundary

Below is the implementation of the Java Regex Finder:

Java




// Java Program to implement regex
import java.io.*;
import java.util.regex.*;
 
// Driver Class
class GFG {
    // Main Function
    public static void main(String[] args)
    {
        // Check if all elements are numbers
        System.out.println(Pattern.matches("\\d+", "1234"));
 
        // Check if all elements are non-numbers
        System.out.println(Pattern.matches("\\D+", "1234"));
 
        // Check if all the elements are non-numbers
        System.out.println(Pattern.matches("\\D+", "Gfg"));
 
        // Check if all the elements are non-spaces
        System.out.println(Pattern.matches("\\S+", "gfg"));
    }
}


Output

true
false
true
true

Conclusion

Lastly, let us do discuss some of the important observations as retrieved from the above article

  1. We create a pattern object by calling Pattern.compile(), there is no constructor. compile() is a static method in the Pattern class.
  2. Like above, we create a Matcher object using matcher() on objects of the Pattern class.
  3. Pattern.matches() is also a static method that is used to check if a given text as a whole matches the pattern or not.
  4. find() is used to find multiple occurrences of patterns in the text.
  5. We can split a text based on a delimiter pattern using the split() method

FAQs in Java Regex

Q1. What are regular expressions in Java?

Ans:

Regular Expressions in java are used for string patterns that can be used for searching, manipulating, and editing a string in Java.

Q2. What is a simple example of regular expression in Java?

Ans:

A simple example of a regular expression in java is mentioned below:

Java




// Java Program to check on Regex
import java.io.*;
import java.util.regex.*;
 
// Driver class
class GFG {
    // Main function
    public static void main(String[] args)
    {
        // Checks if the string matches with the regex
        // Should be single character a to z
        System.out.println(Pattern.matches("[a-z]", "g"));
 
         // Check if all the elements are non-numbers
        System.out.println(Pattern.matches("\\D+", "Gfg"));
 
        // Check if all the elements are non-spaces
        System.out.println(Pattern.matches("\\S+", "gfg"));
    }
}


Output

true
true
true



Previous Article
Next Article

Similar Reads

How to validate an IP address using Regular Expressions in Java
Given an IP address, the task is to validate this IP address with the help of Regular Expressions.The IP address is a string in the form "A.B.C.D", where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.Examples: Input: str = "000.12.12.034" Output: True Input: str =
3 min read
How to validate a Username using Regular Expressions in Java
Given a string str which represents a username, the task is to validate this username with the help of Regular Expressions. A username is considered valid if all the following constraints are satisfied: The username consists of 6 to 30 characters inclusive. If the username consists of less than 6 or greater than 30 characters, then it is an invalid
3 min read
How to validate a Password using Regular Expressions in Java
Given a password, the task is to validate the password with the help of Regular Expression. A password is considered valid if all the following constraints are satisfied: It contains at least 8 characters and at most 20 characters.It contains at least one digit.It contains at least one upper case alphabet.It contains at least one lower case alphabe
3 min read
Validating Bank Account Number Using Regular Expressions
A bank account number is a unique number that is assigned to the account holder after opening their account in any specific bank. In technical terms, we can consider the Bank account number as the Primary Key. A bank account number enables us to do debit, credit, and other transactions. As per RBI Guidelines, Bank Account Number has a unique struct
6 min read
How to Validate a Password using Regular Expressions in Android?
Regular Expression basically defines a search pattern, pattern matching, or string matching. It is present in java.util.regex package. Java Regex API provides 1 interface and 3 classes. They are the following: MatchResult InterfaceMatcher classPattern classPatternSyntaxException class Pattern p = Pattern.compile(".e"); // represents single characte
4 min read
Extracting IP Address From a Given String Using Regular Expressions
Prerequisites: Regular ExpressionsIP addressGiven a string str, the task is to extract all the IP addresses from the given string. Let us see how to extract IP addresses from a file. Input: str="The IPV4 address of Port A is: 257.120.223.13. And the IPV6 address is:fffe:3465:efab:23fe:2235:6565:aaab:0001" Output: 257.120.223.13fffe:3465:efab:23fe:2
4 min read
How to Make Java Regular Expression Case Insensitive in Java?
In this article, we will learn how to make Java Regular Expression case-insensitive in Java. Java Regular Expression is used to find, match, and extract data from character sequences. Java Regular Expressions are case-sensitive by default. But with the help of Regular Expression, we can make the Java Regular Expression case-insensitive. There are t
2 min read
Block Lambda Expressions in Java
Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda's body consists of a block of code. If it has only a single expression they are called "Expression Bodies". Lambdas which contain expression bodies are known as "Expression Lambdas". B
4 min read
Java - Lambda Expressions Parameters
Lambda Expressions are anonymous functions. These functions do not need a name or a class to be used. Lambda expressions are added in Java 8. Lambda expressions basically express instances of functional interfaces An interface with a single abstract method is called a functional interface. One example is java.lang.Runnable. Lambda expressions imple
5 min read
How to Create Thread using Lambda Expressions in Java?
Lambda Expressions are introduced in Java SE8. These expressions are developed for Functional Interfaces. A functional interface is an interface with only one abstract method. To know more about Lambda Expressions click here. Syntax: (argument1, argument2, .. argument n) -> { // statements }; Here we make use of the Runnable Interface. As it is
3 min read
Practice Tags :