Java Regular Expressions

To perform search and manipulation on strings in Java, use Regex i.e., Regular Expressions. To form a search pattern, match or find strings, and search and edit strings, we use Regular Expressions as a sequence of characters. To work with regex in Java, import the java.util.regex package:

  • Pattern Class
  • Matcher Class

Pattern Class

A Pattern class is a compiled representation of a regular expression to define a pattern. For a pattern, call its compile() method to return a Pattern object.

Matcher Class

The Matcher Class performs match operations on a character sequence by interpreting a Pattern. For a Matcher object, call the matcher() method on a Pattern object.

How to write a Regular Expression in Java

To write a Regex in Java, we used both the Pattern and Matcher class. Let us see two examples.

Example 1

In this first example, we will search for a letter in a word with Regular Expressions in Java. If it is found, True gets displayed. The pattern is case insensitive, set using the Flag Pattern.CASE_INSENSITIVE:

Output

Example 2

In the next example, we will find a letter in a word with Regular Expressions in Java:

Output

Regex Quantifiers

To define quantities i.e., the occurrences of a character, Regex in Java has Quantifiers. Here is the list of Quantifiers in Java that matches any string containing,

Regex Quantifiers in Java

Let us now see an example of Quantifiers in Regular Expressions:

Output

Regex Metacharacters

The following are the metacharacters in Regular Expressions and finds,

Regex Metacharacters in Java

Let us now see an example of Metacharacters in Regular Expressions:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java - User Input
Java Enums
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading