Java RegEx

Java Regular Expressions (RegEx)

In Java, Regular Expressions (RegEx) are a powerful tool for pattern matching and string manipulation. They allow you to define complex search patterns, validate user inputs, and perform text transformations efficiently. Java provides the java.util.regex package to work with regular expressions.

What is RegEx?

Regular Expressions are sequences of characters that define search patterns. They are used to:

  1. Search for specific patterns in strings.
  2. Validate inputs such as emails, phone numbers, or passwords.
  3. Split or replace parts of a string based on a pattern.

Example:
The pattern \d{3}-\d{2}-\d{4} can match strings like 123-45-6789 (SSN format).

Java RegEx Framework

The java.util.regex package provides two main classes for working with RegEx:

  1. Pattern: Compiles a RegEx into a pattern that can be used for matching.
  2. Matcher: Performs match operations on text using the pattern.

Syntax of Regular Expressions

SymbolMeaningExample
.Matches any character except newlinea.b matches acb
*Matches 0 or more occurrencesa* matches aaa
+Matches 1 or more occurrencesa+ matches aaa
?Matches 0 or 1 occurrencea? matches a or “
\dMatches any digit\d matches 5
\wMatches any word character\w matches A or 1
\sMatches any whitespace\s matches a space
^Matches the start of a line^abc matches abc
$Matches the end of a lineabc$ matches …abc

Using RegEx in Java

1. Matching a Pattern

You can use the Pattern and Matcher classes to check if a string matches a specific pattern.

Example:

import java.util.regex.*;

public class RegExExample {
public static void main(String[] args) {
String text = "hello123";
String pattern = "\\w+\\d+";

Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);

if (matcher.matches()) {
System.out.println("Pattern matches the text!");
} else {
System.out.println("Pattern does not match.");
}
}
}

Output:

Pattern matches the text!

2. Finding All Matches

The find() method of the Matcher class can be used to find all occurrences of a pattern.

Example:

import java.util.regex.*;

public class FindMatches {
public static void main(String[] args) {
String text = "cat bat rat mat";
String pattern = "\\b\\w{3}\\b"; // Matches any 3-letter word

Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);

while (matcher.find()) {
System.out.println("Found: " + matcher.group());
}
}
}

Output:

Found: cat
Found: bat
Found: rat
Found: mat

3. Replacing Strings

You can use the replaceAll() method to replace parts of a string that match a pattern.

Example:

import java.util.regex.*;

public class ReplaceExample {
public static void main(String[] args) {
String text = "This is a test.";
String pattern = "\\s";

// Replace all spaces with underscores
String result = text.replaceAll(pattern, "_");
System.out.println(result);
}
}

Output:

This_is_a_test.

4. Splitting Strings

The split() method can split a string into an array based on a pattern.

Example:

import java.util.regex.*;

public class SplitExample {
public static void main(String[] args) {
String text = "one,two,three";
String pattern = ",";

String[] result = text.split(pattern);
for (String word : result) {
System.out.println(word);
}
}
}

Output:

one
two
three

Common Use Cases of RegEx

  1. Email Validation
String email = "example@mail.com";
String pattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$";

if (email.matches(pattern)) {
System.out.println("Valid email");
} else {
System.out.println("Invalid email");
}
  1. Password Validation (at least 8 characters, 1 digit, 1 uppercase)
String password = "Pass1234";
String pattern = "^(?=.*[0-9])(?=.*[A-Z]).{8,}$";

if (password.matches(pattern)) {
System.out.println("Valid password");
} else {
System.out.println("Invalid password");
}
  1. Extracting Numbers
String text = "Order ID: 12345";
String pattern = "\\d+";

Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(text);

if (matcher.find()) {
System.out.println("Extracted Number: " + matcher.group());
}

Advantages of Using RegEx in Java

  1. Powerful Pattern Matching: Handles complex search patterns easily.
  2. Efficiency: Reduces the need for multiple loops and conditions.
  3. Built-in Support: Java provides comprehensive support for RegEx in the java.util.regex package.

Leave a Comment