Regex in Java

Introduction

 
In this article, we will learn about Java Regex, and how to use Regex with examples in Java. Java regex is also known as Java Regular Expression.
 

What is Regex in Java? 

 
Regular expressions or Java Regex is an API built to define string patterns that can be used to read, alter, and delete data. For pattern matching with the regular expressions, Java offers java.util.regex bundle.
 
In other words, a regular expression is a special sequence of characters that helps us match or find other strings using a special syntax held in a pattern that is used to search, edit, or manipulate text and data.
 

java.util.regex package

 
This provides regular expressions with three classes and a single interface. The classes Matcher and Pattern are usually used in standard Java language.
 
The complete program of regex package is listed below.
  1. import java.util.regex.Pattern;  
  2.   
  3. public class RegexPackageExample {  
  4.     public static void main(String args[]) {  
  5.         System.out.println(Pattern.matches(".y""toy"));  
  6.         System.out.println(Pattern.matches("s..""sam"));  
  7.         System.out.println(Pattern.matches(".a""mia"));  
  8.     }  
The above program generates the following output.
 
regex_package_example_output 
 

PatternSyntaxException class

 
PatternSyntaxException is a unresolved exception object which means a syntax error in a normal speaking pattern. 
 
The complete program of Showing the PatternSyntaxException class example is listed below.
  1. import java.util.regex.Pattern;  
  2.   
  3. public class PatternSyntaxExceptionExample {  
  4.     public static void main(String... args) {  
  5.         String regex = "["// invalid regex  
  6.         Pattern pattern = Pattern.compile(regex);  
  7.     }   
The above program generates the following output.
 
pattern_syntax_exception_output 
 
Note
 
In the above example program, we use the invalid syntax of regex. So, when we run the program it generates the PatternSyntaxException: Unclosed character class near index 0;
 

java.util.regex.Matcher; 
 

A Matcher entity is a motor that interprets the template against an input string and executes operations of play. Matcher doesn't describe any public builders, as the class Template. By calling the matcher method) (you get a Matcher object on a Pattern object.
 

Methods of Matcher class 

 
public boolean matches()
 
The matches method is used to check the pattern string is matches with matcher string or not. It returns the boolean value. If the string matches, it returns true otherwise false. It does not take any argument. It does not throw any exception.
 
Syntax
 
public boolean matches();
 
The complete program of java.util.regex.Matcher.matches() method is listed below.
  1. import java.util.regex.*;  
  2. public class MatchesMethodExample {  
  3.     public static void main(String[] args) {  
  4.         boolean result;  
  5.         // Get the string value to be checked  
  6.         String value1 = "CsharpCorner";  
  7.   
  8.         // Create a pattern from regex  
  9.         Pattern pattern = Pattern.compile(value1);  
  10.   
  11.         // Get the String value to be matched  
  12.         String value2 = "CsharpC";  
  13.   
  14.         // Create a matcher for the input String  
  15.         Matcher matcher = pattern.matcher(value2);  
  16.   
  17.         // Get the current matcher state  
  18.         System.out.println("result : " + matcher.matches());  
  19.     }  
The above program generates the following output.
 
matches_examplr_method_output
 
public int start() Method
 
The start() method is used to get the start subsequence index. public int start() method does not take any argument. It returns the index of the first character matched 0. If the operation is failed it throws IllegalStateException.
 
Syntax
 
public int start();
 
The complete program of java.util.regex.Matcher.start() method is listed below.
  1. import java.util.regex.*;  
  2.   
  3. public class StartMethodExample {  
  4.     public static void main(String[] args) {  
  5.   
  6.         // Get the string value to be checked  
  7.         String value1  = "CsharpCorner";  
  8.   
  9.         // Create a pattern from regex  
  10.         Pattern pattern = Pattern.compile(value1);  
  11.   
  12.         // Get the String value to be matched  
  13.         String value2 = "Csharp";  
  14.         // Create a matcher for the input String  
  15.         Matcher matcher = pattern.matcher(value2);  
  16.   
  17.         // Get the current matcher state  
  18.         MatchResult result = matcher.toMatchResult();  
  19.         System.out.println("Current Matcher: " + result);  
  20.   
  21.         while (matcher.find()) {  
  22.             // Get the first index of match result  
  23.             System.out.println(matcher.start());  
  24.         }  
  25.     }  
  26. }
The above program generates the following output.
 
Start_method_example_output
 
public boolean find() Method
 
The find method is used to find the next subsequence of the input sequence that finds the pattern.  It returns a boolean value. If the input string matches then it returns true otherwise returns false. This method does not take any argument. This method does not throw any exception.
 
Syntax
 
public boolean find()
 
The complete program of java.util.regex.Matcher.find() method is listed below.
  1. import java.util.regex.*;  
  2. public class FindMethodExample {  
  3.     public static void main(String args[]) {  
  4.         // Get the regex to be checked  
  5.         String value = "CsharpCorner";  
  6.         String value1 = "Java Programming";  
  7.   
  8.         // Create a string from regex  
  9.         Pattern pattern = Pattern.compile(value);  
  10.         Pattern pattern1 = Pattern.compile(value1);  
  11.   
  12.         // Get the String for matching  
  13.         String matchString = "CsharpCorner";  
  14.         String matchString1 ="Java";  
  15.   
  16.         // Create a matcher for the String  
  17.         Matcher match = pattern.matcher(matchString);  
  18.         Matcher match1 = pattern.matcher(matchString1);  
  19.         //find() method  
  20.         System.out.println(match.find());  
  21.         System.out.println(match1.find());  
  22.   
  23.     }  
The above program generates the following output.
 
find_method_example_output
 
public boolean find(int start) Method
 
The find(int start) method is used to find the next subsequence of the input sequence that finds the pattern, according to the given argument. It returns a boolean value. This method does not take any argument. This method throws IndexOutOfBoundException if the given argument is less then zero or greater then the length of the string.
 
Syntax
 
public boolean find(int start);
 
The complete program of java.util.regex.Matcher.find() method is listed below.
  1. import java.util.regex.*;  
  2.   
  3. public class FindMethodExample2 {  
  4.     public static void main(String args[]) {  
  5.         // Get the regex to be checked  
  6.         String value = "CsharpCorner";  
  7.         String value1 = "Java Programming";  
  8.   
  9.         // Create a string from regex  
  10.         Pattern pattern = Pattern.compile(value);  
  11.         Pattern pattern1 = Pattern.compile(value1);  
  12.   
  13.         // Get the String for matching  
  14.         String matchString = "CsharpCorner";  
  15.         String matchString1 = "Java";  
  16.   
  17.         // Create a matcher for the String  
  18.         Matcher match = pattern.matcher(matchString);  
  19.         Matcher match1 = pattern.matcher(matchString1);  
  20.         //find() method  
  21.         System.out.println(match.find(3));  
  22.         System.out.println(match1.find(6));  
  23.   
  24.     }  
The above program generates the following output.
 
find_example_method2_output
 
public int end() Method
 
The end method is used to get the offset after the last match of the character is done. This method doesn't take any argument. this method throws IllegalStateException if the operation fails.
 
Syntax
 
public int end()
 
The complete program example of java.util.regex.Matcher.end() is listed below.
  1. import java.util.regex.*;  
  2. public class endMethodExample {  
  3.     public static void main(String[] args) {  
  4.         // TODO Auto-generated method stub  
  5.         Pattern p=Pattern.compile("Hello C#Corner");  
  6.         Matcher m=p.matcher("Hello C#Corner");  
  7.         if(m.matches())  
  8.             System.out.println("Both are matching till "+m.end()+" character");  
  9.         else  
  10.             System.out.println("Both are not matching"+m.end());  
  11.     }  
The above program generates the following output.
 
end_method_example_output 
 

java.util.regex.Pattern

 
A Pattern object is a compiled representation of a regular expression. There are no Template level public designers. To construct a template, you first need to invoke one of its public static compiles (methods which subsequently return a Template item, which acknowledges a regular expression as the first statement
 
It is the compiled form of a regular expression and is used to describe the Regex engine template.
 

Methods of Pattern class 

 
static Pattern compile(String regex)
 
The compile() method is used to match a text from a regular expression(regex) pattern. If the operation is failed it returns false otherwise true. This method takes a pattern string value as the argument.
 
Syntax
 
static Pattern compile(String regex)
 
The complete program of the java.util.regex.pattern.compile();
  1. import java.util.regex.Matcher;  
  2. import java.util.regex.Pattern;  
  3.   
  4. public class CompileMethodExample {  
  5.   
  6.     public static void main(String args[]) {  
  7.   
  8.         // Get the string value to be checked  
  9.         Pattern p = Pattern.compile(".o");  
  10.           
  11.         //Matcher string for  
  12.         Matcher m = p.matcher("to");  
  13.         boolean m1 = m.matches();  
  14.         System.out.println(m1);  
  15.     }  
  16. }  
The above program generates the following output.
 
compile_method_example_output
 
public boolean matches(regex, String)
 
The matches() method is used to check the given string matches the given regular expression or not. This method returns the boolean value true if the string matches the regex otherwise it returns false.  If the syntax is invalid then this method throws PatternStateException.
 
This method takes two arguments.
  • regex- This argument is the regular expression value which has to check from the string.
     
  • String- This string value has to check from the regex through the matches() method.
The complete program of the public boolean matches(regex, String) method is listed below.
  1. import java.util.regex.Pattern;  
  2.   
  3. public class PatternClassMatchesMethod {  
  4.     public static void main(String args[]) {  
  5.         System.out.println(Pattern.matches("[bad]""abcd"));  
  6.         System.out.println(Pattern.matches("[as]""a"));  
  7.         System.out.println(Pattern.matches("[ass]""asssna"));  
  8.     }  
The above program generates the following output.
 
pattern_class_matches_method_output 
 

Summary

 
In this article, we learned about Java Regular Expression(regex) in Java Programming Language and the varoius methods of regex.