正则与JSON

正则表达式和JSON是常用的数据处理工具,本课学习Java中的使用方法。

正则表达式

正则表达式用于匹配、查找、替换字符串。

基础语法

语法 说明 示例
. 任意字符 a.c 匹配 "abc"
\d 数字 \d+ 匹配 "123"
\w 字母数字下划线 \w+ 匹配 "hello_123"
\s 空白字符 \s+ 匹配空格/制表符
^ 开始 ^Hello 匹配开头
$ 结束 World$ 匹配结尾
* 0次或多次 ab*c 匹配 "ac", "abc"
+ 1次或多次 ab+c 匹配 "abc", "abbc"
? 0次或1次 ab?c 匹配 "ac", "abc"
{n} n次 a{3} 匹配 "aaa"
{n,m} n到m次 a{2,4} 匹配 "aa", "aaa"
[] 字符集 [abc] 匹配 "a", "b", "c"
| cat|dog 匹配 "cat" 或 "dog"
() 分组 (ab)+ 匹配 "ab", "abab"

Pattern和Matcher

JAVA
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexDemo {
    public static void main(String[] args) {
        String text = "我的邮箱是test@example.com,电话是13812345678";
        
        // 匹配邮箱
        Pattern emailPattern = Pattern.compile("\\w+@\\w+\\.\\w+");
        Matcher emailMatcher = emailPattern.matcher(text);
        if (emailMatcher.find()) {
            System.out.println("邮箱:" + emailMatcher.group());
        }
        
        // 匹配电话
        Pattern phonePattern = Pattern.compile("1[3-9]\\d{9}");
        Matcher phoneMatcher = phonePattern.matcher(text);
        if (phoneMatcher.find()) {
            System.out.println("电话:" + phoneMatcher.group());
        }
    }
}

常用方法

JAVA
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexMethods {
    public static void main(String[] args) {
        String text = "Hello 123 World 456 Java 789";
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(text);
        
        // find():查找下一个匹配
        while (matcher.find()) {
            System.out.println("找到:" + matcher.group());
            System.out.println("位置:" + matcher.start() + "-" + matcher.end());
        }
        
        // matches():完全匹配
        System.out.println(Pattern.matches("\\d+", "123"));   // true
        System.out.println(Pattern.matches("\\d+", "123a"));  // false
        
        // split():分割
        String[] parts = "a,b,c".split(",");
        for (String part : parts) {
            System.out.println(part);
        }
        
        // replaceAll():替换
        String result = "Hello 123 World".replaceAll("\\d+", "***");
        System.out.println(result);  // Hello *** World
    }
}

示例:常用正则

JAVA
public class CommonRegex {
    public static void main(String[] args) {
        // 邮箱验证
        String emailRegex = "^[\\w.-]+@[\\w.-]+\\.\\w+$";
        System.out.println(Pattern.matches(emailRegex, "test@example.com"));  // true
        
        // 手机号验证
        String phoneRegex = "^1[3-9]\\d{9}$";
        System.out.println(Pattern.matches(phoneRegex, "13812345678"));  // true
        
        // 身份证验证
        String idCardRegex = "^\\d{17}[\\dXx]$";
        System.out.println(Pattern.matches(idCardRegex, "11010119900101001X"));  // true
        
        // IP地址验证
        String ipRegex = "^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$";
        System.out.println(Pattern.matches(ipRegex, "192.168.1.1"));  // true
    }
}
▶ 试一试

分组捕获

JAVA
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GroupDemo {
    public static void main(String[] args) {
        String text = "2026-06-24";
        Pattern pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
        Matcher matcher = pattern.matcher(text);
        
        if (matcher.matches()) {
            System.out.println("完整日期:" + matcher.group(0));  // 2026-06-24
            System.out.println("年:" + matcher.group(1));       // 2026
            System.out.println("月:" + matcher.group(2));       // 06
            System.out.println("日:" + matcher.group(3));       // 24
        }
    }
}

JSON处理

JSON是轻量级的数据交换格式。

手动解析JSON

JAVA
public class JsonParseDemo {
    public static void main(String[] args) {
        String json = "{\"name\":\"Alice\",\"age\":25,\"city\":\"Beijing\"}";
        
        // 简单解析(不推荐,实际项目用库)
        json = json.replace("{", "").replace("}", "").replace("\"", "");
        String[] pairs = json.split(",");
        
        for (String pair : pairs) {
            String[] kv = pair.split(":");
            System.out.println(kv[0].trim() + " = " + kv[1].trim());
        }
    }
}

使用JSON库(Jackson)

JAVA
// 引入Jackson依赖后使用
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonDemo {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // 对象转JSON
        User user = new User("Alice", 25, "Beijing");
        String json = mapper.writeValueAsString(user);
        System.out.println("JSON:" + json);
        // {"name":"Alice","age":25,"city":"Beijing"}
        
        // JSON转对象
        User parsed = mapper.readValue(json, User.class);
        System.out.println("对象:" + parsed);
    }
}

class User {
    private String name;
    private int age;
    private String city;
    
    public User() {}  // Jackson需要无参构造
    
    public User(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }
    
    // getter/setter
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public String getCity() { return city; }
    public void setCity(String city) { this.city = city; }
    
    @Override
    public String toString() {
        return "User{name='" + name + "', age=" + age + ", city='" + city + "'}";
    }
}

JSON数组

JAVA
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;

public class JsonArrayDemo {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        
        // JSON数组
        String json = "[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30}]";
        
        // 解析为List
        List<User> users = mapper.readValue(json, new TypeReference<List<User>>() {});
        users.forEach(System.out::println);
        
        // List转JSON
        String result = mapper.writeValueAsString(users);
        System.out.println(result);
    }
}

JSON常用操作

JAVA
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonNodeDemo {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"name\":\"Alice\",\"age\":25,\"address\":{\"city\":\"Beijing\",\"zip\":\"100000\"}}";
        
        // 解析为JsonNode
        JsonNode node = mapper.readTree(json);
        
        // 获取值
        System.out.println("name: " + node.get("name").asText());
        System.out.println("age: " + node.get("age").asInt());
        System.out.println("city: " + node.get("address").get("city").asText());
        
        // 判断是否存在
        System.out.println("has email: " + node.has("email"));
    }
}

String的正则方法

JAVA
public class StringRegex {
    public static void main(String[] args) {
        String text = "Hello 123 World 456";
        
        // matches():完全匹配
        System.out.println("123".matches("\\d+"));  // true
        
        // replaceAll():替换所有匹配
        String result = text.replaceAll("\\d+", "***");
        System.out.println(result);  // Hello * World *
        
        // replaceFirst():替换第一个匹配
        String result2 = text.replaceFirst("\\d+", "***");
        System.out.println(result2);  // Hello *** World 456
        
        // split():分割
        String[] parts = "a,b,,c".split(",");  // 保留空串
        System.out.println(parts.length);  // 4
        
        String[] parts2 = "a,b,,c".split(",", -1);  // 保留尾部空串
        System.out.println(parts2.length);  // 4
    }
}

❓ 常见问题

Q 正则表达式太难记不住怎么办?
A 记住常用的\d \w \s . * + ? [] ()即可,复杂的查文档。
Q Java中用哪个JSON库?
A Jackson最流行,Gson也不错。简单场景可以手动解析。
Q 正则表达式性能怎么样?
A 简单正则性能很好,复杂正则可能有性能问题。避免回溯过多。

📖 小节

📝 作业

  1. 邮箱验证: 编写方法验证邮箱格式
  2. 文本提取: 从HTML中提取所有链接
  3. JSON解析: 解析JSON字符串,提取指定字段

下一课

下一课我们将学习 综合项目,完成一个完整的Java项目。

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏