Regular Expressions in Java

mudacodes
2 min readNov 12, 2023

--

Photo by Alexander Sinn on Unsplash

Regular expressions, often referred to as regex or regexp, are powerful tools for pattern matching and manipulation of strings. In Java, the java.util.regex package provides robust support for regular expressions, allowing developers to perform complex string operations efficiently. In this post, we'll explore the fundamentals of regular expressions in Java, delve into the Pattern and Matcher classes, and provide practical examples to help you master this essential skill.

Understanding Basics:

1. What is a Regular Expression?

A regular expression is a sequence of characters that defines a search pattern. It consists of literal characters and special characters (metacharacters) that convey meaning. In Java, regular expressions are represented by the Pattern class.

2. Basic Syntax:

  • .: Matches any character.
  • ^: Anchors the regex at the beginning of the line.
  • $: Anchors the regex at the end of the line.
  • []: Defines a character class.
  • |: Acts as a logical OR.

Using the Pattern Class:

1. Creating a Pattern:

import java.util.regex.Pattern;
String regex = "hello";
Pattern pattern = Pattern.compile(regex);

2. Matching:

String text = "hello world";
boolean isMatch = pattern.matcher(text).find();
System.out.println("Is there a match? " + isMatch);

Matcher Class for Advanced Operations:

1. Extracting Matches:

import java.util.regex.Matcher;
String text = "The price is $20 and $30";
Pattern pattern = Pattern.compile("\\$\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("Match: " + matcher.group());
}

2. Grouping

String text = "Date: 2023-11-13";
Pattern pattern = Pattern.compile("Date: (\\d{4}-\\d{2}-\\d{2})");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
System.out.println("Captured group (date): " + matcher.group(1));
}

Advanced Techniques:

1. Quantifiers:

String text = "abcc";
Pattern pattern = Pattern.compile("ab+c");
boolean isMatch = pattern.matcher(text).matches();
System.out.println("Is there a match? " + isMatch);

2. Lookahead and Lookbehind:

String text = "apple orange banana";
Pattern pattern = Pattern.compile("\\b(?!orange\\b)\\w+\\b");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println("Match: " + matcher.group());

Conclusion:

Regular expressions in Java are a powerful tool for string manipulation and pattern matching. Understanding their syntax, using the Pattern and Matcher classes effectively, and exploring advanced techniques will empower you to handle complex string operations with ease. Practice these examples, experiment with different patterns, and unlock the full potential of regular expressions in your Java projects. Happy coding!

--

--