本文目录导读:

我来给你几个Java正则表达式提取的实用案例:
基础提取示例
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexDemo {
public static void main(String[] args) {
// 案例1:提取所有数字
String text = "订单号:A12345,金额:1000.50元,数量:3件";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(text);
System.out.println("提取到的数字:");
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}
分组提取(提取特定部分)
public class GroupExtractDemo {
public static void main(String[] args) {
// 案例2:提取邮箱用户名和域名
String email = "zhangsan@qq.com";
Pattern pattern = Pattern.compile("(\\w+)@(\\w+\\.\\w+)");
Matcher matcher = pattern.matcher(email);
if (matcher.find()) {
System.out.println("完整邮箱: " + matcher.group(0));
System.out.println("用户名: " + matcher.group(1));
System.out.println("域名: " + matcher.group(2));
}
// 案例3:提取日期各部分
String date = "日期:2024-01-15";
Pattern datePattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher dateMatcher = datePattern.matcher(date);
if (dateMatcher.find()) {
System.out.println("年: " + dateMatcher.group(1));
System.out.println("月: " + dateMatcher.group(2));
System.out.println("日: " + dateMatcher.group(3));
}
}
}
提取多个匹配项到列表
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ListExtractDemo {
public static void main(String[] args) {
// 案例4:从文本中提取所有手机号
String text = "联系人1:13812345678,联系人2:13998765432,联系人3:15811112222";
// 匹配手机号(简单模式:1开头,11位数字)
List<String> phones = extractMatches(text, "1[3-9]\\d{9}");
System.out.println("提取的手机号:" + phones);
// 案例5:提取所有URL
String content = "访问 https://www.example.com 或 http://test.cn 获取更多信息";
List<String> urls = extractMatches(content, "https?://[\\w.]+");
System.out.println("提取的URL:" + urls);
}
// 通用方法:从文本中提取所有匹配项
public static List<String> extractMatches(String text, String regex) {
List<String> matches = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
matches.add(matcher.group());
}
return matches;
}
}
复杂的业务场景提取
public class BusinessExtractDemo {
public static void main(String[] args) {
// 案例6:从日志中提取关键信息
String log = """
[2024-01-15 10:30:45] INFO - User:admin login success from IP:192.168.1.100
[2024-01-15 10:31:20] ERROR - Database connection failed, User:test
[2024-01-15 10:32:15] INFO - User:zhangsan logout from IP:10.0.0.5
""";
// 提取所有IP地址
List<String> ips = extractMatches(log, "\\d+\\.\\d+\\.\\d+\\.\\d+");
System.out.println("所有IP:" + ips);
// 提取所有用户名
List<String> users = extractMatches(log, "(?<=User:)\\w+");
System.out.println("所有用户:" + users);
// 案例7:从HTML中提取链接
String html = """
<a href="https://www.baidu.com">百度</a>
<a href="https://www.google.com">谷歌</a>
""";
Pattern linkPattern = Pattern.compile("href=\"([^\"]+)\">([^<]+)");
Matcher linkMatcher = linkPattern.matcher(html);
while (linkMatcher.find()) {
System.out.println("链接: " + linkMatcher.group(1) +
", 文本: " + linkMatcher.group(2));
}
}
public static List<String> extractMatches(String text, String regex) {
List<String> matches = new ArrayList<>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
matches.add(matcher.group());
}
return matches;
}
}
命名分组提取(Java 7+)
public class NamedGroupDemo {
public static void main(String[] args) {
// 案例8:使用命名分组使代码更清晰
String record = "张三,30岁,北京,13812345678";
Pattern pattern = Pattern.compile(
"(?<name>\\w+),(?<age>\\d+)岁,(?<city>\\w+),(?<phone>1[3-9]\\d{9})"
);
Matcher matcher = pattern.matcher(record);
if (matcher.find()) {
System.out.println("姓名: " + matcher.group("name"));
System.out.println("年龄: " + matcher.group("age"));
System.out.println("城市: " + matcher.group("city"));
System.out.println("电话: " + matcher.group("phone"));
}
}
}
实用工具类
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexUtils {
// 提取所有匹配项
public static List<String> extractAll(String text, String regex) {
List<String> results = new ArrayList<>();
Matcher matcher = Pattern.compile(regex).matcher(text);
while (matcher.find()) {
results.add(matcher.group());
}
return results;
}
// 提取带分组信息
public static List<Map<String, String>> extractWithGroups(String text,
String regex,
String[] groupNames) {
List<Map<String, String>> results = new ArrayList<>();
Matcher matcher = Pattern.compile(regex).matcher(text);
while (matcher.find()) {
Map<String, String> groupMap = new HashMap<>();
for (String name : groupNames) {
groupMap.put(name, matcher.group(name));
}
results.add(groupMap);
}
return results;
}
// 判断是否完全匹配
public static boolean isMatch(String text, String regex) {
return Pattern.matches(regex, text);
}
public static void main(String[] args) {
// 测试工具类
String data = "产品A:100元, 产品B:200元, 产品C:300元";
// 提取所有价格
List<String> prices = extractAll(data, "\\d+元");
System.out.println("价格列表: " + prices);
// 提取产品名和价格
List<Map<String, String>> products = extractWithGroups(
data,
"(?<name>产品\\w):(?<price>\\d+)元",
new String[]{"name", "price"}
);
for (Map<String, String> product : products) {
System.out.println("产品: " + product.get("name") +
", 价格: " + product.get("price") + "元");
}
}
}
常用正则表达式速查表
// 中文字符
String chineseRegex = "[\\u4e00-\\u9fa5]+";
// 邮箱
String emailRegex = "\\w+@\\w+\\.\\w+";
// 手机号
String phoneRegex = "1[3-9]\\d{9}";
// 身份证号(简单版)
String idCardRegex = "\\d{17}[0-9Xx]";
// IP地址
String ipRegex = "(\\d{1,3}\\.){3}\\d{1,3}";
// URL
String urlRegex = "https?://[\\w\\-./?=&]+";
// 日期 (2024-01-15)
String dateRegex = "\\d{4}-\\d{2}-\\d{2}";
这些案例覆盖了大部分常见的正则提取需求,你可以根据实际场景调整正则表达式,记得在处理正则时加上必要的转义字符,并注意性能问题(长文本用Pattern预编译)。