Java 正则表达式
正则表达式是一种强大的文本处理工具,它允许我们基于特定模式搜索、匹配和操作字符串。在Java中,正则表达式通过java.util.regex
包提供支持,主要包含Pattern
和Matcher
两个核心类。掌握正则表达式可以大幅提高我们处理文本的效率。
什么是正则表达式?
正则表达式(Regular Expression,简称regex)是一种用特定语法编写的模式,用来描述和匹配一系列符合某个句法规则的字符串。简单来说,它是一种用于文本搜索和替换的"模板"。
思考一下
想象你需要验证用户输入的是否是有效的电子邮箱地址,或者从一段文本中提取所有电话号码,手动编写代码会很复杂,而正则表达式可以用简洁的方式解决这些问题。
Java 中的正则表达式基础
在Java中使用正则表达式主要依靠两个类:
java.util.regex.Pattern
:编译正则表达式为模式java.util.regex.Matcher
:使用模式对字符串执行匹配操作
基本使用步骤
- 编译正则表达式模式
- 获取匹配器
- 使用匹配器进行操作
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexBasic {
public static void main(String[] args) {
// 1. 编译正则表达式
Pattern pattern = Pattern.compile("Hello");
// 2. 获取匹配器
Matcher matcher = pattern.matcher("Hello World");
// 3. 进行匹配操作
boolean found = matcher.find();
System.out.println("匹配结果: " + found);
}
}
输出:
匹配结果: true
正则表达式语法
基本字符匹配
表达式 | 说明 |
---|---|
x | 字符x |
. | 任何字符 |
\d | 数字: [0-9] |
\D | 非数字: [^0-9] |
\s | 空白字符: [ \t\n\x0B\f\r] |
\S | 非空白字符: [^\s] |
\w | 单词字符: [a-zA-Z_0-9] |
\W | 非单词字符 |
量词
表达式 | 说明 |
---|---|
X? | X出现一次或不出现 |
X* | X出现零次或多次 |
X+ | X出现一次或多次 |
X{n} | X恰好出现n次 |
X{n,} | X至少出现n次 |
X{n,m} | X至少出现n次,但不超过m次 |
字符类
方括号[]
内的字符表示"匹配其中任意一个字符":
Pattern pattern = Pattern.compile("[abc]"); // 匹配a、b或c中的任意一个
Matcher matcher = pattern.matcher("apple");
boolean found = matcher.find();
System.out.println(found); // 输出: true,因为"apple"包含"a"
边界匹配
表达式 | 说明 |
---|---|
^ | 行的开头 |
$ | 行的结尾 |
\b | 单词边界 |
\B | 非单词边界 |
常用正则表达式方法
matches()方法
matches()
方法检查整个字符串是否与模式匹配:
String text = "Hello123";
boolean isMatch = text.matches("\\w+");
System.out.println(isMatch); // 输出: true
find()和group()方法
find()
方法查找下一个匹配,group()
返回匹配的子串:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("There are 123 apples and 456 oranges");
while (matcher.find()) {
System.out.println("找到: " + matcher.group());
}
输出:
找到: 123
找到: 456
替换方法
replaceAll()
和replaceFirst()
用于替换匹配的内容:
String text = "My phone number is 123-456-7890";
String newText = text.replaceAll("\\d+", "XXX");
System.out.println(newText); // 输出: My phone number is XXX-XXX-XXX