Java中的正则表达式(Regular Expression)

230 阅读2分钟

一.正则表达式的概念

正则表达式(简称 regex)是一种强大的文本处理工具,用于匹配、查找、替换字符串中的特定模式。它由一系列特殊字符和普通字符组成,可以定义复杂的搜索模式。

二.正则表达式的引用方式

1.基本用法示例

在Java中,正则表达式主要通过Java.util.regex的两个包实现:

  • Pattern:编译后的正则表达式模式
  • Matcher:用于对字符串执行匹配操作的引擎
import java.util.regex.*;

public class RegexExample {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog.";
        String patternString = "fox";
        
        // 1. 创建Pattern对象
        Pattern pattern = Pattern.compile(patternString);
        
        // 2. 创建Matcher对象
        Matcher matcher = pattern.matcher(text);
        
        // 3. 查找匹配
        if (matcher.find()) {
            System.out.println("Found '" + matcher.group() + "' at position " + matcher.start());
        } else {
            System.out.println("No match found.");
        }
    }
}

2. 常用正则表达式元字符

元字符描述示例
.匹配任意单个字符a.c 匹配 "abc", "a1c"
^匹配字符串开头^The 匹配以 "The" 开头的字符串
$匹配字符串结尾dog.$ 匹配以 "dog." 结尾的字符串
*匹配前一个字符0次或多次ab*c 匹配 "ac", "abc", "abbc"
+匹配前一个字符1次或多次ab+c 匹配 "abc", "abbc" 但不匹配 "ac"
?匹配前一个字符0次或1次colou?r 匹配 "color" 和 "colour"
\d匹配数字\d\d 匹配两个连续数字
\w匹配单词字符(字母、数字、下划线)\w+ 匹配一个或多个单词字符
[]匹配括号内的任意字符[aeiou] 匹配任何元音字母
[^]匹配不在括号内的任意字符[^aeiou] 匹配非元音字符
``或操作`catdog` 匹配 "cat" 或 "dog"

三.正则表达式的实用场景示例

1. 验证电子邮件格式

public boolean isValidEmail(String email) {
    String regex = "^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,}$";
    return email.matches(regex);
}

2. 提取字符串中的所有数字

public List<String> extractNumbers(String text) {
    List<String> numbers = new ArrayList<>();
    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = pattern.matcher(text);
    
    while (matcher.find()) {
        numbers.add(matcher.group());
    }
    
    return numbers;
}

3. 替换字符串中的特定内容

public String replaceDates(String text) {
    // 将 MM/DD/YYYY 格式替换为 YYYY-MM-DD
    return text.replaceAll("(\\d{2})/(\\d{2})/(\\d{4})", "$3-$1-$2");
}

4. 分割字符串

public String[] splitByCommas(String text) {
    // 按逗号分割,忽略前后空格
    return text.split("\\s*,\\s*");
}

5.注意事项

  1. Java 中正则表达式需要双重转义:

    • \d 表示数字(在正则中通常写作 \d
    • \\ 表示单个反斜杠(在正则中写作 \
  2. 常用方法:

    • String.matches(regex):检查整个字符串是否匹配
    • String.split(regex):按正则分割字符串
    • String.replaceAll(regex, replacement):替换所有匹配项
    • String.replaceFirst(regex, replacement):替换第一个匹配项
  3. 对于复杂或频繁使用的正则表达式,建议预编译 Pattern 对象以提高性能。

四.总结

正则表达式是一个非常强大的工具,掌握它可以极大地提高文本处理的效率和灵活性。