Skip to content
Related Articles

Related Articles

Improve Article
Regular Expressions in Java
  • Difficulty Level : Medium
  • Last Updated : 05 Nov, 2019

Regular Expressions or Regex (in short) 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 few areas of strings where Regex are widely used to define the constraints. Regular Expressions 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:

ClassDescription
util.regex.PatternUsed for defining patterns
util.regex.MatcherUsed for performing match operations on text using patterns
PatternSyntaxExceptionUsed for indicating syntax error in a regular expression pattern

MatchResult interface: This interface is used to determine the result of a match operation for a regular expression. It must be noted that although the match boundaries, groups and group boundaries can be seen, the modification is not allowed through a MatchResult.

Modifier and TypeMethodDescription
intend()It is used to return the offset after the last character matched.
intend(int group)It is used to return the offset after the last character of the subsequence captured by the given group during this match.
Stringgroup()It is used to return the input subsequence matched by the previous match.
Stringgroup(int group)It is used to return the input subsequence captured by the given group during the previous match operation.
intgroupCount()It is used to return the number of capturing groups in this match result’s pattern.
intstart()It is used to return the start index of the match.
intstart(int group)It is used to return the start index of the subsequence captured by the given group during this match.
  1. java.util.regex.Pattern class: This class is a compilation of regular expressions that can be used to define various types of patters, providing no public constructors. This can be created by invoking the compile() method which accepts a regular expression as the first argument, thus returns a pattern after execution.
    Modifier and TypeMethodDescription
    static Patterncompile(String regex)It is used to compile the given regular expression into a pattern.
    static Patterncompile(String regex, int flags)It is used to compile the given regular expression into a pattern with the given flags.
    intflags()It is used to return this pattern’s match flags.
    Matchermatcher(CharSequence input)It is used to create a matcher that will match the given input against this pattern.
    static booleanmatches(String regex, CharSequence input)It is used to compile the given regular expression and attempts to match the given input against it.
    Stringpattern()It is used to return the regular expression from which this pattern was compiled.
    static Stringquote(String s)It is used to return a literal pattern String for the specified String.
    String[]split(CharSequence input)It is used to split the given input sequence around matches of this pattern.
    String[]split(CharSequence input, int limit)It is used to split the given input sequence around matches of this pattern.
    StringtoString()It is used to return the string representation of this pattern.




    // 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[])
        {
            // 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"));
        }
    }
  2. java.util.regex.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.
    Modifier and TypeMethodDescription
    booleanfind()It is mainly used for searching multiple occurrences of the regular expressions in the text.
    booleanfind(int start)It is used for searching occurrences of the regular expressions in the text starting from the given index.
    intstart()It is used for getting the start index of a match that is being found using find() method.
    intend()It is used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character.
    intgroupCount()It is used to find the total number of the matched subsequence.
    Stringgroup()It is used to find the matched subsequence.
    booleanmatches()It is used to test whether the regular expression matches the pattern.

    Note that 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 pattern in text.

    Java Programs to demonstrate workings of compile(), find(), start(), end() and split() :



    1. Java Program to demonstrate simple pattern searching




      // 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("geeks");
        
              // Search above pattern in "geeksforgeeks.org"
              Matcher m = pattern.matcher("geeksforgeeks.org");
        
              // 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));
          }
      }

      Output:

      Pattern found from 0 to 4
      Pattern found from 8 to 12
    2. Java Program to demonstrate simple regular expression searching




      // 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("ge*");
        
              // Search above pattern in "geeksforgeeks.org"
              Matcher m = pattern.matcher("geeksforgeeks.org");
        
              // 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));
          }
      }

      Output:

      Pattern found from 0 to 2
      Pattern found from 8 to 10
      Pattern found from 16 to 16
      
    3. Java program to demonstrate Case Insensitive Searching




      // 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("ge*", Pattern.CASE_INSENSITIVE);
        
              // Search above pattern in "geeksforgeeks.org"
              Matcher m = pattern.matcher("GeeksforGeeks.org");
        
              // 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));
          }
      }

      Output:

      Pattern found from 0 to 2
      Pattern found from 8 to 10
      Pattern found from 16 to 16
      
    4. Java program to demonstrate working of split() to split a text based on a delimiter pattern




      // Java program to demonstrate working of splitting a text by a
      // given pattern
      import java.util.regex.Matcher;
      import java.util.regex.Pattern;
        
      class Demo
      {
          public static void main(String args[])
          {
              String text = "geeks1for2geeks3";
        
              // 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);
          }
      }

      Output:

      geeks
      for
      geeks
      
  3. PatternSyntaxException class: This object of Regex is used to indicate a syntax error in a regular expression pattern and is an unchecked exception.
    Modifier and TypeMethodDescription
    StringgetDescription()It is used to retrieve the description of the error.
    intgetIndex()It is used to retrieve the error index.
    StringgetMessage()It is used to return a multi-line string containing the description of the syntax error and its index, the erroneous regular-expression pattern, and a visual indication of the error index within the pattern.
    StringgetPattern()It is used to retrieve the erroneous regular-expression pattern.

Important Observations/Facts:

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

Articles based on Java Regular Expression:

Recent articles on Java Regular Expressions

This article is contributed by Akash Ojha. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :