Java Regular Expression (Java Regex) with Examples

1. Objective

We closed our last chapter on Java Array. Today, we start a new chapter – Java Regular Expression(regex) in which we will study working and types of regular expressions of Java. Moreover, we will discuss how and when Java Regex used.

So, let’s begin Java Regular Expression Tutorial.

Introduction of Java Regular Expression

Java Regular Expression – Introduction

2. What is Java Regular Expression

A regular expression in Java is also known as Regex, they are an API used for patterns for strings and further, they can use for editing, manipulating, and searching of texts. They are usually used with Java strings as their constraints such as a password. They are provided under the package java.util.regex.

The java.util.regex consists of 3 classes, they are

  • regex.Pattern – This class is used to define patterns for Java classes
  • regex.Matche – It is used to check for matching operators in Java on text using patterns.
  • PatternSyntaxException – This class is used for indicating the errors in the Java syntax of a regular expression.

Do you know What is Lambda Expression in Java?

3. Java.util.regex.Pattern class

Java Regular Expression

Java Regular Expression – Java.util.regex.Pattern Class

Java Pattern class has 3 types-

a. Matches

Matches are used to check the whole text with a pattern, its output is Java boolean.
Example

// A Simple Java program to demonstrate working of Pattern.matches() in Java
import java.util.regex.Pattern;
 class Demo
{
    public static void main(String args[])
    {
        //  line prints "true" because the whole text "dataflair" matches the pattern "datafla*r"
        System.out.println (Pattern.matches("dataflair*r",
                                            "dataflair"));
        // line prints "false" because the whole text "dataflai" doesn't match the pattern "d*taf*"
        System.out.println (Pattern.matches("d*taf*",
                                            "dataflai"));
    }
}

b. Compile()

Compile() use to compile a given string which may contain regular expressions and create a pattern. An input to this may contain flags such as Pattern.COMMENTS, Pattern.CASE_INSENSITIVE etc.

c. Split()

Split() use to split a text into multiple strings on the basis of delimiter pattern.

Read about Design Patterns in Java – Creational, Behavioural, & Structural

4. Java.util.regex.Matcher Class

Java Regular Expression – Java.util.regex.Matcher Class

Java Matcher class has 3 types-

a. Find()

Find() basically, use for searching multiple occurrences of Java regular expression in any text.

b. Start()

Start() use to find the index of the result found by find().

c. End()

End() is used to find the end index of the result found by find(), it returns an index of Java character next to last matching character.

Let’s revise Java Number Methods with Syntax and Examples

5.  Example to Demonstrate Workings

a. Simple pattern searching in Java

// A Simple Java program to demonstrate working of string matching in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo
{
    public static void main(String args[])
    {
        // Create a pattern to be searched
        Pattern pattern = Pattern.compile("flair");
        // Search above pattern in "dataflair.com"
        Matcher m = pattern.matcher("dataflair.com");
        // Print starting and ending indexes of the pattern in text
        while (m.find())
            System.out.println("Pattern found from " + m.start() +
                               " to " + (m.end()-1));
    }
}

b. Simple regular expression searching in java

// A Simple Java program to demonstrate working of String matching in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo
{
    public static void main(String args[])
    {
        // Create a pattern to be searched
        Pattern pattern = Pattern.compile("fl*");
        // Search above pattern in "dataflair.com"
        Matcher m = pattern.matcher("dataflair.com");
        // Print starting and ending indexes of the pattern in text
        while (m.find())
            System.out.println("Pattern found from " + m.start() +
                               " to " + (m.end()-1));
    }
}

c. Case Insensitive Searching in java

// A Simple Java program to demonstrate working of string matching in Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo
{
    public static void main(String args[])
    {
        // Create a pattern to be searched
        Pattern pattern = Pattern.compile("da*", Pattern.CASE_INSENSITIVE)
        // Search above pattern in "dataflair.com"
        Matcher m = pattern.matcher("Dataflair.com");
        while (m.find())
            System.out.println("Pattern from “ + m.start() +
                               " to " + (m.end()-1));
    }
}

Do you know Polymorphism in Java

d. Working of split()

It is based to split a text based on a delimiter pattern in java

import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Demo
{
    public static void main(String args[])
    {
        String text = "data1flair2demo3";
        // Specifies the string pattern which is to be searched
        String delimiter =  "\\d";
        Pattern pattern = Pattern.compile(delimiter,
                                        Pattern.CASE_INSENSITIVE);
        // Used to perform case insensitive search of the string
        String[] result = pattern.split(text);
       for (String temp: result)
            System.out.println(temp);
    }
}

So, this was all about Java Regular Expression Tutorial. hope you like our explanation.

6. Conclusion

Hence, we learned about various regular expressions used in Java and how Java regular expressions use in a program with their examples. This will help us learn and understand the future tutorials better and code better. Furthermore, if you have any query, feel free to ask in a comment box.
See also – Java Operators

For reference

Leave a Reply

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