正则表达式(Regular Expression,简称 Regex)是一种用于匹配字符串的模式工具。在 Java 中,正则表达式通过 java.util.regex
包实现,主要涉及以下两个类:
Pattern
:表示一个编译好的正则表达式模式。Matcher
:用于在字符串中查找与模式匹配的内容。正则表达式可以用来验证格式、提取信息或替换文本,例如检查邮箱地址是否合法、提取字符串中的数字、按规则分割字符串等。
以下是正则表达式的常用符号和元字符(以正则表达式的原始形式列出)。在 Java 代码中,符号如 \d
需要写成 \\d
,因为 Java 字符串需要转义反斜杠。
符号 | 含义 | 示例 | 不匹配示例 |
---|---|---|---|
\d |
匹配一个数字(0-9) | 5 |
a |
\D |
匹配一个非数字 | a |
5 |
\w |
匹配字母、数字或下划线 | a 、3 或 _ |
! |
\W |
匹配非字母、数字或下划线 | ! 或 @ |
a |
\s |
匹配一个空白字符(如空格、制表符、换行符) | 或 \n |
a |
\S |
匹配一个非空白字符 | a 或 1 |
空白字符 |
. |
匹配任意字符(除换行符外) | a 或 1 或 . |
\n |
字符集合用方括号 []
表示,用于匹配单个字符。以下是详细说明:
符号 | 含义 | 示例 | 不匹配示例 |
---|---|---|---|
[abc] |
匹配单个字符,且该字符是 a 、b 或 c |
a 、b 或 c |
ab (多字符)、d |
[^abc] |
匹配单个字符,且该字符不是 a 、b 或 c |
d 或 1 |
a 、b 或 c |
[a-z] |
匹配单个小写字母(a 到 z) | b |
A 、1 |
[A-Z] |
匹配单个大写字母(A 到 Z) | B |
a 、1 |
[a-zA-Z] |
匹配单个字母(大小写均可) | A 或 b |
1 |
[0-9] |
匹配单个数字(0 到 9) | 5 |
a |
[a-z&[def]] |
匹配单个字符,且该字符是 a 到 z 中且是 d 、e 或 f |
d 、e 或 f |
a 、b |
[a-z&&[^bc]] |
匹配单个字符,且该字符是 a 到 z 但不是 b 或 c |
a 或 d |
b 、c |
[a-z&&[^m-p]] |
匹配单个字符,且该字符是 a 到 z 但不是 m 到 p | a 或 q |
m 、n |
说明:[abc]
只匹配单个字符,不会匹配连续的字符串。例如:
ab
:[abc]
会匹配 a
(第一个字符),再匹配 b
(第二个字符),但不能直接匹配整个 ab
。ab
,需要写成 ab
(连续字符模式),而不是 [ab]
。量词用于指定匹配的次数:
符号 | 含义 | 示例 | 不匹配示例 |
---|---|---|---|
+ |
匹配 1 次或多次 | \d+ 匹配 123 |
空字符串 |
* |
匹配 0 次或多次 | \d* 匹配 12 或空 |
无 |
? |
匹配 0 次或 1 次 | \d? 匹配 1 或空 |
12 (多于 1 个) |
{n} |
匹配正好 n 次 | \d{2} 匹配 12 |
1 、123 |
{n,} |
匹配至少 n 次 | \d{2,} 匹配 123 |
1 |
{n,m} |
匹配 n 到 m 次 | \d{2,3} 匹配 12 或 123 |
1 、1234 |
符号 | 含义 | 示例 | 不匹配示例 |
---|---|---|---|
^ |
匹配字符串的开头 | ^a 匹配 abc 的开头 |
bac |
$ |
匹配字符串的结尾 | a$ 匹配 cba 的结尾 |
abc |
\b |
匹配单词边界 | \bword\b 匹配单独的 word |
keyword |
Java 提供了两种主要方式来使用正则表达式:通过 Pattern
和 Matcher
类,或者直接使用 String
类的方法。
Pattern
和 Matcher
步骤:
Pattern.compile()
创建正则表达式模式(注意转义)。Pattern.matcher()
创建一个匹配器。Matcher.find()
和 Matcher.group()
查找并获取匹配结果。示例代码:提取字符串中的所有数字,并展示字符集合的匹配。
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexDemo {
public static void main(String[] args) {
// 示例 1:提取数字
String input = "Order: 123, Price: 456";
Pattern pattern = Pattern.compile("\\d+"); // 正则表达式 \d+(匹配 1 个或多个数字)
Matcher matcher = pattern.matcher(input);
System.out.println("提取的数字:");
while (matcher.find()) {
System.out.println(matcher.group());
}
// 示例 2:字符集合 [abc] 的匹配
String text = "ab";
Pattern pattern2 = Pattern.compile("[abc]"); // 正则表达式 [abc](匹配单个 a、b 或 c)
Matcher matcher2 = pattern2.matcher(text);
System.out.println("\n字符集合 [abc] 匹配结果:");
while (matcher2.find()) {
System.out.println("匹配到的字符:" + matcher2.group());
}
}
}
运行结果:
提取的数字:
123
456
字符集合 [abc] 匹配结果:
匹配到的字符:a
匹配到的字符:b
说明:在字符串 ab
中,[abc]
每次只匹配一个字符,先匹配到 a
,再匹配到 b
,但它不会将 ab
作为一个整体匹配。
String
类的方法String
类提供了几种简便的方法:
matches()
:判断整个字符串是否完全匹配正则表达式。 String text = "12345";
boolean isNumber = text.matches("\\d+"); // 返回 true
System.out.println("是否全为数字:" + isNumber);
replaceAll()
:替换所有匹配正则表达式的部分。 String text = "abc123def456";
String result = text.replaceAll("\\d+", "-"); // 结果:abc-def-
System.out.println("替换数字后的结果:" + result);
split()
:按正则表达式分割字符串。 String text = "a,b,c";
String[] parts = text.split(","); // 结果:["a", "b", "c"]
System.out.println("分割结果:" + java.util.Arrays.toString(parts));
public class EmailValidation {
public static void main(String[] args) {
String email = "[email protected]";
String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
if (email.matches(emailPattern)) {
System.out.println("邮箱格式正确:" + email);
} else {
System.out.println("邮箱格式错误:" + email);
}
}
}
运行结果:
邮箱格式正确:[email protected]
public class PhoneValidation {
public static void main(String[] args) {
String phone = "13812345678";
String phonePattern = "^1[3-9]\\d{9}$";
if (phone.matches(phonePattern)) {
System.out.println("手机号码格式正确:" + phone);
} else {
System.out.println("手机号码格式错误:" + phone);
}
}
}
运行结果:
手机号码格式正确:13812345678
public class WordExtraction {
public static void main(String[] args) {
String input = "Hello world, this is a test";
Pattern pattern = Pattern.compile("\\b\\w+\\b"); // 正则表达式 \b\w+\b(匹配单词)
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("找到的单词:" + matcher.group());
}
}
}
运行结果:
找到的单词:Hello
找到的单词:world
找到的单词:this
找到的单词:is
找到的单词:a
找到的单词:test
如果需要匹配连续的字符(如 ab
),不能使用 [ab]
,而是直接写成 ab
:
public class SequenceMatch {
public static void main(String[] args) {
String input = "cabd";
Pattern pattern = Pattern.compile("ab"); // 正则表达式 ab(匹配连续的 ab)
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println("找到的连续字符:" + matcher.group());
}
}
}
运行结果:
找到的连续字符:ab
Pattern.compile()
,建议将 Pattern
对象定义为静态变量。.
、+
)需要转义,在 Java 中需要双重转义,例如正则表达式 \.
要写成 \\.
。