Java Regular Expression (RegEx) Explained [Easy Examples]

Related Searches: java regex, java regex tester, java regular expression, java pattern, java regex matcher, java pattern matcher, java string matches, java regex example, java regex pattern, java string regex, java regular expression tester, java string matches regex, java regular expression example, java util regex pattern, java regex tutorial, java regex checker, pattern class in java, java pattern matcher example, java pattern example, java matcher example, java regex match any string, convert string to regex java, java regex pattern tester, how to check regular expression in java, how to use pattern in java, validate regex online java, java regex pattern compile, java regular expression pattern matching, create regex java

 

Introduction to Java regular expression (Java Regex)

A Java regular expression is a special sequence of characters that helps us to match or find other strings or sets of strings, using a specified syntax held in a pattern. They can be used to search, edit, or manipulate text and data. In this tutorial, we will learn about the Java regex. We will cover see the some of basic java regular expressions and will use them in our java program.

Advertisement

At the same time, we will also cover three different types of java classes that help us to deal with the Java regex by providing us various kinds of methods. We will cover some of those methods using examples. All in all, this tutorial will contain all the important information and methods that you need to learn in order to start working with the regular expression.

 

Getting started with Java regular expression (Java Regex)

As we already discussed that a Java regex is a group of characters that helps in matching the patterns in a String or a set of Strings, using a particular syntax of a pattern. Java provides Regular Expressions that are useful for defining patterns in a String which can ultimately be helpful in performing various operations on String/text like searching, processing, editing, pattern matching, manipulating, email and password validation, etc. In this section, we will get started with regular expressions and will look at some of the java classes that provide different methods to work with java regex.

 

Metacharacters of Java Regex

Now we are already familiar with Java regex, in this section, we will have a look at some of the Metacharacters and their meaning in the java programming language and will also discuss different classes as well. See the list of metacharacters and their meaning below:

  • .   : Any character (may or may not match terminator).
  • \d : Any digits  [ 0-9 ].
  • \D : Any non-digit  [ ^0-9 ] (except 0 – 9).
  • \w : Any word character [ a-z A-Z _0-9 ].
  • \W : Any non-word character  [ ^\w ].
  • \s : Any whitespace character  [ \t \n \f \r \x0B ].
  • \S : Any non-whitespace character  [ ^\s ].
  • \b : A word boundary.
  • \B : A non-word boundary.

Java also provides the following different classes that are used to work with regular expressions.  See the list of classes below:

  • util.regex.Pattern : It is used to create or define java patterns/java regular expressions.
  • util.regex.Matcher<b> </b>: It is used to interpret the pattern and perform match operations against an input string.
  • util.regex.PatternSyntaxException : It is used to throw an exception if the syntax of a java regex is incorrect.

In the following sections, we will discuss the above-mentioned classes in more detail and will solve various examples.

 

Java regular expressions in java.util.Pattern class

The Pattern class in java is used to define or create regular expressions or patterns. This class is a compiled representation of regular expressions that can be used to define various types of patterns. There is no public constructor in the Pattern class. We can use the public static method compile() of this class by passing regular expression as an argument which will create the pattern object after execution. In the following, sections we will have a look at some of the important methods that are available in this class and will solve an example as well.

Advertisement

 

Different Methods of Java Pattern Class

Now let us have a look at some of the methods that are available in the java pattern class. In this section, we will list some of the important methods and will give a short description of each. See the table below which contains some of those methods:

MethodsDescription
static Pattern compile(String regex)This method compiles the specified regular expression into a pattern.
static Pattern compile(String regex, int flags)This method is similar to the above method but takes one more argument called flag and is used to compile the given regular expression into a pattern with the given flags.
Matcher matcher(CharSequence input)It creates a matcher that will match the given input against this pattern.
static boolean matches(String regex, CharSequence input)It is used to compile the given regular expression to match the given input String against it.
String pattern()This method is used to return the regular expression from which we compiled this pattern.
static String quote(String s)It is used to return a literal pattern String for the stated/input String.

 

Example of Pattern class

Now, we are already familiar with some of the methods of the java pattern class, let us now solve a real example using this class. See the example below:

// importing regex class
import java.util.regex.*;
// java main class
public class Main{
  // java main method
  public static void main(String args[])
  {
    // printing match one:
    System.out.println("Matching one is:");
    //Using compile() matches() and matcher() methods 
    // return true
    boolean match1=Pattern.compile("lin.x").matcher("linux").matches();
    //  printing out the matching one
    System.out.println(match1);
    // printing
    System.out.println("Matching two is:");
    // .. represents 2 characters
    // also returns true
    boolean match2 = Pattern.matches("clo..", "cloud");
    // printing match two
    System.out.println(match2);
    // printing
    System.out.println("Matching three is:");
    // .. .represents 2 characters
    // returns false
    boolean match3 = Pattern.matches("golinux..", "golinuxcloud");
    // printing match three
    System.out.println(match3);
  }
}

Output:

Matching one is:
true
Matching two is:
true
Matching three is:
false

Notice that we get true for the first two matches because the pattern matches with the actual words while we get false for the third one because the pattern was not similar to the actual word.

 

Java regular expression in util.regex.Matcher class

The object of the Matcher class is an engine that is used to perform match operations of a given regular expression against an input string for multiple times. It finds multiple occurrences of the regular expressions in the input text/string. Like the Pattern class, Matcher too has no public constructors. We can obtain an object of the Matcher class from any object of Pattern class by invoking the matcher() method. In this section, will discuss some of the methods that are available in this class and solve an example using this class as well.

 

Different Methods of Java Matcher class

Now let us have a look at some of the methods that are available in the matcher class which helps us to perform different operations. See the table below which shows the method names and a little description about them.

MethodsDescription
int start():It is used to get the start index of the last character which is matched using find() method.
int end():It is used to get the end index of the last character which is matched using find() method.
boolean find():It is used to find multiple occurrences of the input sequence that matches the pattern.
boolean find(int start):It attempts to find the occurrences of the input sequence that matches the pattern, starting at the specified index.
boolean matches():It attempts to match the entire text against the pattern.
String replaceFirst(String Replacement):Replaces the first subsequence of the input sequence that matches the pattern with the specified replacement string.
String replaceAll(String Replacement):Replaces every subsequence of the input sequence that matches the pattern with the specified replacement string.

Advertisement

 

Example-1 Matcher class of Case sensitive search

Now we already know some of the methods of the matcher class and their usage. Let us now take an example to see how we can use the matcher class for case sensitivie search. See the example below:

// importing regex
import java.util.regex.*;
// java main class
public class Main {
  // java main method
  public static void main(String args[]){
    //Case Sensitive Searching
    // Creating new pattern "linux" for search
    Pattern pattern = Pattern.compile("Linux");
    // Searching linux in the given pattern
    Matcher match = pattern.matcher("GoLinuxcloud");
    // Printing start and end indexes of the pattern in text
    System.out.println("The following is the result of search:");
    // using while loop
    while (match.find())
      // printing the pattern index
      System.out.println("Pattern index starts from " + match.start() +
          " to " + (match.end()-1));
  }

}

Output:

Pattern index starts from 2 to 6

Notice that the word Linux starts from index two and ends at index 6 and we get the right output.

 

Example-2 Matcher class search of case insensitive search

Now let us take another example of case insensitive search using the matcher class. See the example below:

// importing regex
import java.util.regex.*;
// java main class
public class Main {
  // java main method
  public static void main(String args[]){
    //Case Insensitive Searching
    // creating pattern of linux with lower case
    Pattern pattern1= Pattern.compile("linux", Pattern.CASE_INSENSITIVE);
    // Searching linux the word linux in the GoLinuxcloud
    Matcher match1 = pattern1.matcher("GoLinuxcloud");
    // using while loop
    while (match1.find())
      // printing the index of search
      System.out.println("Pattern starts from " + match1.start() +
          " to " + (match1.end()-1)); 
  }

}

Output:

Pattern starts from 2 to 6

Notice that the word was in lower case but still managed to search and match with the upper case one.

 

Java regular expressions in java.util.PatternSyntaxException Class

This class throws an unchecked exception to indicate a syntax error in a regular-expression pattern. This class too contains many different types of methods that are used to deal with java regexs. In the following sections, we will discuss some of those methods and will solve an example as well.

 

Different Methods of Java PatternSyntaxException Class

Now let us have a look at some of the methods of the PatternSyntaxException class. See the following table which contains some of the useful methods and descriptions of them.

MethodsDescription
String getDescription():

It is used to get the description of the error.
int getIndex():It is used to get the index of the error.
String getMessage():

This method gives a multiple-line string, describing the syntax error along with its index
String getPattern():It is used to get the erroneous regular-expression pattern.

 

Example of PatternSyntaxException class

Now we already know some of the methods that are available in the PatterSyntaxException class.  Let us now take an example of PatternSyntaxException class. See the following example.

// importing regex
import java.util.regex.*;
// java main method
public class Main {
  // creating some statice varibles of type private
   private static String REGEX = "[";
   private static String INPUT = "Welcome to " + "Golinuxcould.org";
   private static String REPLACE = "com";
   // java main method
   public static void main(String[] args) {
      // try block to handle error
      try{
        // creating pattern
         Pattern pattern = Pattern.compile(REGEX);
         // get a matcher object
         Matcher matcher = pattern.matcher(INPUT); 
         // replacing
         INPUT = matcher.replaceAll(REPLACE);
      } 
      // catching the patternSyntaxException
      catch(PatternSyntaxException e){
         System.out.println("PatternSyntaxException: ");
         System.out.println("Description: "+ e.getDescription());
         System.out.println("Index: "+ e.getIndex());
         System.out.println("Message: "+ e.getMessage());
         System.out.println("Pattern: "+ e.getPattern());
      }
   }
}

Output:

PatternSyntaxException:
Description: Unclosed character class
Index: 0
Message: Unclosed character class near index 0
[
^
Pattern: [

Notice that in the above example, first, we created some private variables which can only be accessed through the methods. Then inside the try block, we tried to apply pattern matcher and replaceAll method but PatternSyntaxException occurs which was successfully handle inside the catch block.

 

Summary

Java Regular Expression or Regex 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. In this tutorial, we learned about java regexs. We learned about the metacharacters of java regex. We also covered the three different classes that provide different methods to perform different operations on java regex. For example pattern class, matcher class, and PatternSyntaxException class.

We also covered the methods that are available in these classes and solve various examples. All in all, this tutorial contains all the necessary information about java regex in order to get started working with them.

 

Further Reading

Java regular expression
Java pattern class
Java matcher class

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment