Regular Expressions (Regex) are a powerful tool in Java for pattern matching and searching in strings. Whether you’re validating email addresses, searching for patterns, or replacing text, Regex simplifies these tasks with concise and efficient syntax. In this tutorial by The Coding College, we’ll explore Java’s support for Regex through the java.util.regex
package.
What is a Regular Expression?
A regular expression is a sequence of characters that defines a search pattern. It is used to:
- Search for specific patterns in strings.
- Validate input (e.g., email, phone numbers).
- Replace text based on patterns.
The java.util.regex
Package
Java provides the java.util.regex
package for working with regular expressions. It consists of two main classes:
Pattern
: Compiles the regular expression into a pattern.Matcher
: Matches the compiled pattern against an input string.
Syntax for Regular Expressions
Some common Regex symbols include:
Symbol | Description | Example |
---|---|---|
. | Any character (except newline) | h.t matches hat , hit |
* | 0 or more occurrences | ho* matches h , ho , hoo |
+ | 1 or more occurrences | ho+ matches ho , hoo |
? | 0 or 1 occurrence | ho? matches h , ho |
[] | Any character in brackets | [abc] matches a , b , c |
^ | Starts with | ^Hello matches Hello World |
$ | Ends with | World$ matches Hello World |
\d | Digit (0-9) | \d matches 5 |
\w | Word character (a-z, A-Z, 0-9, _) | \w matches A |
\s | Whitespace | \s matches a space |
Example: Validating an Email Address
Code:
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String email = "[email protected]";
String regex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
if (matcher.matches()) {
System.out.println("Valid Email Address");
} else {
System.out.println("Invalid Email Address");
}
}
}
Output:
Valid Email Address
Searching for Patterns
You can use Regex to find patterns within a string using the find()
method of the Matcher
class.
Code:
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String text = "Learn Java at The Coding College";
String regex = "\\bJava\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
System.out.println("Found the word 'Java'");
} else {
System.out.println("Word not found");
}
}
}
Output:
Found the word 'Java'
Replacing Patterns
The replaceAll()
method is used to replace substrings that match a pattern.
Code:
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String text = "The price is 100 dollars";
String regex = "\\d+";
String replacedText = text.replaceAll(regex, "XXX");
System.out.println(replacedText);
}
}
Output:
The price is XXX dollars
Splitting Strings
You can split strings into arrays based on a pattern using the split()
method.
Code:
import java.util.regex.*;
public class Main {
public static void main(String[] args) {
String text = "apple,banana,orange";
String regex = ",";
String[] fruits = text.split(regex);
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Output:
apple
banana
orange
Common Use Cases for Regex in Java
- Input Validation:
- Emails, phone numbers, ZIP codes, etc.
- Text Processing:
- Search and replace.
- Log Analysis:
- Extracting specific information from logs.
Best Practices for Regex in Java
- Escape Special Characters: Use double backslashes (
\\
) for escaping special characters like.
or\d
. - Use Readable Patterns: Write clear and descriptive Regex patterns.
- Pre-compile Patterns: If the same pattern is used repeatedly, compile it once using
Pattern.compile()
for better performance.
Conclusion
Regular expressions are a powerful feature in Java for working with text and patterns. Whether you’re validating input or processing text, Regex can simplify your tasks significantly. Start practicing with the examples provided and explore more features to master this skill.
For more programming tutorials, visit The Coding College and continue learning with us!