杰瑞科技汇

replace java 正则

方法 类型 参数 功能 示例
replace(char old, char new) String 两个 char 将字符串中所有旧字符替换为新字符。 "hello".replace('l', 'p') -> "heppo"
replace(CharSequence old, CharSequence new) String 两个 CharSequence 将字符串中所有旧子串替换为新子串。 "hello world".replace("world", "java") -> "hello java"
replaceAll(String regex, String replacement) String 一个正则表达式,一个替换字符串 将字符串中所有匹配正则表达式的部分替换为新字符串。 "123abc".replaceAll("\\d", "#") -> "###abc"
replaceFirst(String regex, String replacement) String 一个正则表达式,一个替换字符串 将字符串中第一个匹配正则表达式的部分替换为新字符串。 "123abc".replaceFirst("\\d", "#") -> "#23abc"

replace() 方法(非正则替换)

replace() 方法用于简单的、直接的字符串替换,它不将第一个参数视为正则表达式,而是作为普通的字面字符或子串。

a) replace(char oldChar, char newChar)

  • 功能:用新的字符替换所有旧的字符。
  • 参数
    • oldChar: 要被替换的旧字符。
    • newChar: 用来替换的新字符。
  • 特点:非常简单,只处理单个字符。
public class ReplaceCharExample {
    public static void main(String[] args) {
        String str = "hello world, hello java";
        // 将所有 'l' 替换为 'p'
        String newStr = str.replace('l', 'p');
        System.out.println("原始字符串: " + str);
        System.out.println("替换后字符串: " + newStr); // 输出: heppo worpd, heppo java
    }
}

b) replace(CharSequence target, CharSequence replacement)

  • 功能:用新的子串替换所有旧的子串,这是最常用的 replace 方法。
  • 参数
    • target: 要被替换的旧子串(CharSequenceStringStringBuilder 等的父接口)。
    • replacement: 用来替换的新子串。
  • 特点:处理子串,同样不涉及正则表达式,性能通常比 replaceAll 更好。
public class ReplaceStringExample {
    public static void main(String[] args) {
        String str = "I like apples, and I like oranges too.";
        // 将所有 "like" 替换为 "love"
        String newStr = str.replace("like", "love");
        System.out.println("原始字符串: " + str);
        System.out.println("替换后字符串: " + newStr); // 输出: I love apples, and I love oranges too.
    }
}

replaceAll()replaceFirst() 方法(正则替换)

这两个方法使用正则表达式来查找要替换的内容,功能更强大也更灵活。

a) replaceAll(String regex, String replacement)

  • 功能:使用给定的正则表达式 regex 匹配字符串中的所有部分,并将每个匹配项替换为 replacement 字符串。
  • 参数
    • regex: 正则表达式。注意regex 中包含正则的特殊字符(如 [ ] ^ \),需要用 \ 进行转义。
    • replacement: 替换字符串,可以包含特殊的反向引用(如 $1, $2)。

关键点:转义字符

在 Java 字符串中,\ 是一个转义字符,如果你想在正则表达式中匹配一个字面上的 ,你需要写成 \\.

public class ReplaceAllExample {
    public static void main(String[] args) {
        String str = "The price is 100.99, and the ID is A1B2C3.";
        // 示例1: 将所有数字替换为 "#"
        // 正则表达式 \d 表示任意一个数字
        String result1 = str.replaceAll("\\d", "#");
        System.out.println("替换数字后: " + result1);
        // 输出: The price is ###.##, and the ID is #1#2#3.
        // 示例2: 将所有连续的数字替换为 "[NUM]"
        // 正则表达式 \d+ 表示一个或多个连续的数字
        String result2 = str.replaceAll("\\d+", "[NUM]");
        System.out.println("替换连续数字后: " + result2);
        // 输出: The price is [NUM], and the ID is [NUM].
        // 示例3: 删除所有标点符号
        // 正则表达式 [^a-zA-Z0-9\s] 表示任何非字母、非数字、非空白字符
        String result3 = str.replaceAll("[^a-zA-Z0-9\\s]", "");
        System.out.println("删除标点后: " + result3);
        // 输出: The price is 10099 and the ID is A1B2C3
    }
}

反向引用 (Backreferences)

replacement 字符串中的 $n 可以引用正则表达式中的第 n 个捕获组。

public class BackreferenceExample {
    public static void main(String[] args) {
        String str = "John Doe, Jane Smith, Peter Jones";
        // 目标:交换名字和姓氏,格式变为 "Doe John"
        // 正则表达式 ([A-Za-z]+) ([A-Za-z]+) 捕获两个组
        // $1 是第一个捕获组 (名字), $2 是第二个捕获组 (姓氏)
        String result = str.replaceAll("([A-Za-z]+) ([A-Za-z]+)", "$2 $1");
        System.out.println("原始字符串: " + str);
        System.out.println("交换后: " + result);
        // 输出: Doe John, Smith Jane, Jones Peter
    }
}

b) replaceFirst(String regex, String replacement)

  • 功能:与 replaceAll 类似,但它只替换第一个匹配正则表达式的部分。
  • 参数:与 replaceAll 相同。
public class ReplaceFirstExample {
    public static void main(String[] args) {
        String str = "123 456 789";
        // 只替换第一个匹配的数字
        String result = str.replaceFirst("\\d", "#");
        System.out.println("原始字符串: " + str);
        System.out.println("替换第一个数字后: " + result);
        // 输出: #23 456 789
    }
}

如何选择?

  1. 简单替换(替换固定字符或子串)

    • 优先使用 replace(CharSequence target, CharSequence replacement)
    • 它不涉及正则表达式解析,性能更好,代码意图更清晰,不易出错。
  2. 复杂替换(基于模式匹配)

    • 如果需要匹配的不是一个固定的字符串,而是某种模式(如所有数字、所有邮箱地址、所有特定格式的单词等),必须使用 replaceAll()replaceFirst()
  3. 只替换第一个匹配项

    • 使用 replaceFirst()

性能考量

对于简单的字符串替换,replace() 通常比 replaceAll() 更快,因为 replaceAll() 需要额外的步骤来编译正则表达式,如果你的替换逻辑非常简单,并且不需要正则的强大功能,replace() 是更好的选择。

总结表格

场景 推荐方法 理由
替换一个特定的字符 replace(char, char) 最直接、最高效。
替换一个特定的子串 replace(String, String) 比正则更简单、性能更好。
替换所有符合某种模式的子串 replaceAll(regex, replacement) 正则表达式提供了强大的模式匹配能力。
只替换第一个符合某种模式的子串 replaceFirst(regex, replacement) 正则表达式,但只处理第一个匹配项。

希望这个详细的解释能帮助你完全理解 Java 中替换方法的区别和用法!

分享:
扫描分享到社交APP
上一篇
下一篇