Java Regex | Regular Expression

It is an ordinary expression, a set of characters making up the search pattern. If you want to see data in a text field, this search pattern can be used to describe what you look for. There may be a single character or a more complex pattern in a regular expression. In performing all types of searches and replacing text operations, regular expressions can be used.

What is a regular expression in Java?

The regular expression class in Java is not instantiated, but we can create it by importing java.util. A regular expression package that will work with regular expressions. The package contains the following classes:

  • Pattern Class – The pattern class specifies the pattern to use in the search.
  • Matcher Class – The matcher class that is used to find the pattern.
  • PatternSyntaxException class – Indicates a syntax error in a regular expression pattern.

Example:

Do you find any mentions of “Techvidvan” in the sentence:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main{
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("Techvidvan", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher("Visit Techvidvan!");
    boolean matchFound = matcher.find();
    if(matchFound) {
      System.out.println("Match found");
    } 
else {
      System.out.println("Match not found");
    }
  }
}

Output:
Match found

Example explained:

The sentence in this example searches for the word “Techvidvan”. First, the pattern was created using a pattern. Use the compile() method to compile.

The first parameter indicates which pattern to search for, and the second parameter has a flag indicating that the search should be case insensitive. The second parameter is not needed.

You can find a pattern in strings using the matcher() method. A comparison object is returned that contains information about the search performed. If a pattern has been detected in the string and is not recognized, find() returns false.

Java regex

Java Regex The Java Regex or RegularExpression API is used to define a pattern for searching and manipulating strings. Defining restrictions on strings, e.g. password and email security, is widely used.

You can use the Java regex checker tool to try out your normal expressions once you’ve learned the Java regex lesson. In java.util, there are 1 interface and 3 classes provided by the Java Regex API. regex package.

java.util.regex package:

Java’s ability to generate regular expressions is provided by the Matcher and Pattern classes. java.util. regex packages are provided with the following classes and interfaces for normal expressions.

Flags:

The way the lookup is done is changed by using flags in the compile() method. A few of them are given below:

Pattern.CASE_INSENSITIVE: The case of the letter is not considered during the search.

Pattern. LITERAL: The characters in the pattern have no special meaning and should be treated as normal characters when searching.

Pattern. UNICODE_CASE: Additionally, use this to ignore non-English uppercase and lowercase letters when using the CASE_INSENSITIVE flag.

Matches all strings that contain more than one n matches any string with zero or more occurrences of n Matches any string with zero or one occurrence of n matches a string with the sequence X n Matches every string that’s got X to Y n in it Specifies any string with a sequence in the range of X n.

java regex

Java Regular expression patterns:

  • The first parameter of the Pattern.compile() method is the pattern. It describes what is being searched for.
  • Parentheses are used to find a range of characters:
Expression Description
[abc] Find one character from the options between the parentheses.
[^abc] Find a single NOT character between the parentheses.
[0-9] Find one character from 0 to 9.

Metacharacters:

Metacharacters are characters with special meaning:

Metacharacter Description
| Find a match for any of the patterns separated by | as in: cat|dog|fish
. Any character cannot be found to have one occurrence.
^ Matches the beginning of a string as in: ^Hello
$ As in: World$Matches at the end of the string 
\d Find the digit 
\s Find the blank character 
\b You can find a match at the beginning of a word like this: bWORD, or at the end of a word like this: bWORD. 
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers:

Quantifiers define quantities:

Quantifier Description
n+ Matches all strings that contain more than one n.
n* Matches any string with zero or more occurrences of n .
n? Matches any string with zero or one occurrence of n.
n{x} Matches a string with the sequence X n
n{x,y} Matches every string that’s got X to Y n in it Specifies.
n{x,} any string with a sequence in the range of X n.

Matchmaker class:

Implements the MatchResult interface. It is a regular expression engine used to perform matching operations on a sequence of characters.

S.No Method Description
1 boolean matches() test if the regular expression matches the pattern.
2 boolean find() finds another expression that matches the pattern.
3 boolean find(int start) finds the next expression that matches the pattern from the given starting number
4 String group() return the corresponding subsequence. 
5 int start() returns an initial index to the related subsequence.
6 int end() The end index of the appropriate subsequence is returned. 
7 int groupCount() The total number of matching subsequences is returned. 

Pattern class:

That’s a compiled version of the regular expression. Used to define a pattern for the ordinary expression module.

S.No Method Description
1 static Pattern compile(String regex) The given regular expression is compiled and returned an instance of the pattern.
2 Matchmatcherer (CharSequence input) Creates a matcher that’s identical to the pattern input.
3 static boolean matches(String regex, CharSequence input) This is just a combination of the compile and compare methods. Compiles a regular expression that will match an input according to the pattern.
4 String[] split(CharSequence input) The input string is broken down into matches of the given pattern.
5 String pattern() It returns a regular expression pattern.

Conclusion

In a Java program, a regular expression is defined by a string that obeys specific pattern-matching rules. When executing code, the Java machine compiles this string into a Pattern object and uses a Matcher object to find matches in the text.