A Regular Expression (Regex) is a pattern used to search, match, and validate text. In Java, regular expressions are commonly used for checking email formats, finding numbers, replacing text, and validating user input.
Java provides the java.util.regex package
for working with regular expressions.
Two important classes are:
Pattern — represents a regular expression pattern.Matcher — performs matching operations on text.Example: the pattern "cat" matches the word "cat".
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(
Pattern.matches("cat", "cat")
);
System.out.println(
Pattern.matches("cat", "dog")
);
}
}
true
false
Pattern.matches() checks whether the entire
input matches the pattern, not just a part of the input.
Use Pattern.compile() to create a pattern
and matcher() to check text against it.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("Java");
Matcher matcher = pattern.matcher("I am learning Java");
System.out.println(matcher.find());
}
}
true
The find() method returns
true when it finds a matching part
of the text.
| Pattern | Meaning | Example Match |
|---|---|---|
. |
Matches one character except line terminators by default. | c.t matches cat |
^ |
Beginning of input or line, depending on mode. | ^Java |
$ |
End of input or line, depending on mode. | Java$ |
* |
Zero or more repetitions. | ab* matches a, ab, abb |
+ |
One or more repetitions. | ab+ matches ab, abb |
? |
Zero or one repetition. | colou?r |
[abc] |
Matches one listed character. | a, b, or c |
[0-9] |
Matches one digit. | 5 |
{2} |
Exactly two repetitions of the preceding item. | [0-9]{2} |
Use \\d in a Java string to represent the
regex digit pattern \d.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(
Pattern.matches("\\d+", "12345")
);
System.out.println(
Pattern.matches("\\d+", "12abc")
);
}
}
true
false
Here, \\d+ means one or more digits.
The entire input must contain only digits for
Pattern.matches() to return true.
The pattern [a-zA-Z]+ matches one or more
English letters, including uppercase and lowercase letters.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
System.out.println(
Pattern.matches("[a-zA-Z]+", "Java")
);
System.out.println(
Pattern.matches("[a-zA-Z]+", "Java123")
);
}
}
true
false
The second input contains digits, so it does not match the letters-only pattern.
Use Matcher.find() to locate numbers
inside a larger string.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
String text = "I have 25 books and 10 pens.";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
25
10
The group() method returns the text
matched by the most recent successful match.
The replaceAll() method replaces every
part of a string that matches a regular expression.
public class Main {
public static void main(String[] args) {
String text = "Java123 is easy456";
String result = text.replaceAll("\\d+", "");
System.out.println(result);
}
}
Java is easy
The pattern \\d+ matches one or more
digits, which are removed in this example.
The split() method can divide a string
using a regular expression as the separator.
public class Main {
public static void main(String[] args) {
String text = "Apple,Banana,Orange";
String[] fruits = text.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Apple
Banana
Orange
You can also split on one or more spaces using
"\\s+".
For a simple example, the following pattern checks whether a string contains exactly 10 digits.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String mobile = "9876543210";
boolean valid = Pattern.matches(
"[0-9]{10}",
mobile
);
System.out.println("Valid: " + valid);
}
}
Valid: true
A simple regular expression can check the basic shape of an email address.
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String email = "student@example.com";
String regex = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
boolean valid = Pattern.matches(regex, email);
System.out.println("Valid format: " + valid);
}
}
Valid format: true
Use Pattern.CASE_INSENSITIVE when uppercase
and lowercase differences should be ignored.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile(
"java",
Pattern.CASE_INSENSITIVE
);
Matcher matcher = pattern.matcher("I LIKE JAVA");
System.out.println(matcher.find());
}
}
true
| Regex | Meaning |
|---|---|
\\d |
A digit. |
\\D |
A non-digit. |
\\s |
A whitespace character. |
\\S |
A non-whitespace character. |
\\w |
A word character, typically a letter, digit, or underscore in default mode. |
\\W |
A character that is not a word character. |
[A-Z] |
An uppercase English letter. |
[a-z] |
A lowercase English letter. |
[0-9]{4} |
Exactly four digits. |
^Hello |
Text beginning with Hello. |
"\\d+"
in Java code to pass \d+ to the regex engine.
"12345" contains only digits."Hello" contains only English letters."I am 20 years old and have 5 books."."Java123Programming456"."Red,Green,Blue" into separate words."Java" in a sentence."python" in a sentence.Select the correct answer for each question.