Regular expressions (Regex) are powerful tools for pattern matching and text manipulation. In Java, Regex is often used to search, match, and replace substrings within a string based on specific patterns. It’s a key skill for developers dealing with text processing, validation, or data extraction.
What is Regex?
A Regular Expression is a sequence of characters that form a search pattern. It allows you to describe text patterns that can match one or more strings. In Java, you can use the Pattern
and Matcher
classes to work with regular expressions.
Common Uses of Regex in Java
- Searching for patterns: Check if a string matches a specific format (e.g., email, phone number).
- Replacing parts of a string: Modify strings based on matching patterns.
- Validating input: Ensure user input matches a certain format, like validating a password.
- Extracting data: Pull specific information out of text, such as extracting dates from a string.
Basics of Regex Syntax
Regex syntax can seem a little daunting at first, but once you understand the basics, you can create powerful patterns. Here are a few important components:
- Metacharacters: These are special characters that have specific meanings in regex:
.
(dot): Matches any single character (except newline).^
: Anchors the match at the beginning of the string.$
: Anchors the match at the end of the string.\d
: Matches any digit (0-9).\w
: Matches any word character (letters, digits, underscores).\s
: Matches any whitespace character (spaces, tabs, etc.).
Using Pattern and Matcher
In Java, the Pattern
class is used to define a compiled regex expression, and the Matcher
class is used to search through a string. Let’s look at how you can use these classes to perform basic regex tasks:
Example: Checking if a String Matches a Pattern
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String text = "hello123"; String regex = "\\w+"; // Matches one or more word characters Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); if (matcher.matches()) { System.out.println("The string matches the pattern!"); } else { System.out.println("The string does not match the pattern."); } } } |
In this example, the regex \w+
matches one or more word characters. The matcher.matches()
method checks if the entire string matches the pattern.
Example: Finding All Matches in a String
You can also use Matcher
to find all occurrences of a pattern within a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String text = "My phone number is 123-456-7890, and my friend's is 987-654-3210."; String regex = "\\d{3}-\\d{3}-\\d{4}"; // Matches phone numbers in the format XXX-XXX-XXXX Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(text); while (matcher.find()) { System.out.println("Found a phone number: " + matcher.group()); } } } |
This code will find and print all phone numbers that match the pattern XXX-XXX-XXXX
in the provided text.
Example: Replacing Text with Regex
You can use regex to replace parts of a string that match a specific pattern.
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.util.regex.*; public class RegexExample { public static void main(String[] args) { String text = "I love Java, but Python is fun too!"; String regex = "Java"; String replacement = "JavaScript"; String result = text.replaceAll(regex, replacement); System.out.println(result); // "I love JavaScript, but Python is fun too!" } } |
In this case, replaceAll
replaces every occurrence of “Java” with “JavaScript” in the string.