Java 正则表达式提取字符串
在 Java 中,可以使用正则表达式来提取字符串中的特定部分,以下是几种常用的方法:
使用 Pattern 和 Matcher 类
import java.util.regex.*;
public class RegexExample {
public static void main(String[] args) {
String text = "订单号:ORD123456,金额:¥999.99,日期:2025-05-15";
// 提取订单号
Pattern orderPattern = Pattern.compile("订单号:(\\w+)");
Matcher orderMatcher = orderPattern.matcher(text);
if (orderMatcher.find()) {
String orderNumber = orderMatcher.group(1);
System.out.println("订单号: " + orderNumber);
}
// 提取金额
Pattern amountPattern = Pattern.compile("金额:¥(\\d+\\.\\d+)");
Matcher amountMatcher = amountPattern.matcher(text);
if (amountMatcher.find()) {
String amount = amountMatcher.group(1);
System.out.println("金额: " + amount);
}
}
}
使用 String.split() 方法
String text = "apple,banana,orange,grape";
String[] fruits = text.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
使用 String.replaceAll() 或 String.replaceFirst() 方法
String text = "电话:13812345678,邮箱:test@example.com";
String phone = text.replaceAll(".*电话:(\\d+).*", "$1");
System.out.println("电话: " + phone);
String email = text.replaceFirst(".*邮箱:(\\w+@\\w+\\.\\w+).*", "$1");
System.out.println("邮箱: " + email);
使用 Pattern 的 splitAsStream() 方法(Java 8+)
import java.util.regex.*;
import java.util.stream.*;
String text = "name:John,age:30,city:New York";
Pattern pattern = Pattern.compile(",");
pattern.splitAsStream(text)
.forEach(part -> {
String[] keyValue = part.split(":");
if (keyValue.length == 2) {
System.out.println(keyValue[0] + " -> " + keyValue[1]);
}
});
提取多个匹配项
import java.util.regex.*;
import java.util.*;
String text = "ID:1001,Name:Tom;ID:1002,Name:Jerry;ID:1003,Name:Spike";
Pattern pattern = Pattern.compile("ID:(\\d+),Name:(\\w+)");
Matcher matcher = pattern.matcher(text);
List<Map<String, String>> records = new ArrayList<>();
while (matcher.find()) {
Map<String, String> record = new HashMap<>();
record.put("id", matcher.group(1));
record.put("name", matcher.group(2));
records.add(record);
}
records.forEach(System.out::println);
常用正则表达式示例
| 用途 | 正则表达式 | 示例 |
|---|---|---|
| 提取数字 | \\d+ |
"abc123" → "123" |
| 提取字母 | [a-zA-Z]+ |
"abc123" → "abc" |
| 提取邮箱 | \\w+@\\w+\\.\\w+ |
"邮箱:test@example.com" → "test@example.com" |
| 提取日期 | \\d{4}-\\d{2}-\\d{2} |
"日期:2025-05-15" → "2025-05-15" |
| 提取手机号 | 1[3-9]\\d{9} |
"手机:13812345678" → "13812345678" |
注意事项
- 正则表达式中的特殊字符需要转义,如 、、、、
^、、、、[、]、、、、\ - 使用
Matcher.group()方法时,索引从 0 开始,group(0) 表示整个匹配的字符串 - 在循环中使用
Matcher.find()之前,确保调用reset()方法重置匹配器状态
希望这些示例能帮助你在 Java 中使用正则表达式提取字符串!
