本文主要介绍Java中字符串替换,进行多个子字符串同时替换,并且指定每个子字符串的开始和结束的下标,进行替换成占位符。

示例效果

"my email is foo@bar.com and my number is (213)-XXX-XXXX"

替换成

"my email is [EMAIL_ADDRESS] and my number is [PHONE_NUMBER]"

1、指定位置替换代码

import java.util.ArrayList;
import java.util.List;
public class Test {
    public static void main(String[] args) {
        String text = "my email is foo@bar.com and my number is (213)-XXX-XXXX";
        List<Token> findings = new ArrayList<>();
		//指定要替换的子字符串的范围,及要替换成的占位符
        findings.add(new Token(12, 22, "EMAIL_ADDRESS"));
        findings.add(new Token(41, 54, "PHONE_NUMBER"));
        System.out.println(replace(text, findings));
    }
    public static String replace(String text, List<Token> findings) {
        int position = 0;
        StringBuilder result = new StringBuilder();
        for (Token finding : findings) {
            result.append(text.substring(position, finding.start));
            result.append('[').append(finding.type).append(']');
            position = finding.end + 1;
        }
        return result.append(text.substring(position)).toString();
    }
}
class Token {
    int start, end;
    String type;
    Token(int start, int end, String type) {
        this.start = start;
        this.end = end;
        this.type = type;
    }
}

2、字符串替换方法

在Java 中,String 类提供了 3 种字符串替换方法,分别是 replace()、replaceFirst() 和 replaceAll()

1) replace() 方法

replace()方法用于将目标字符串中的指定字符(串)替换成新的字符(串)

replace(String oldChar, String newChar)

2) replaceFirst() 方法

replaceFirst()方法用于将目标字符串中匹配某正则表达式的第一个子字符串替换成新的字符串

replaceFirst(String regex, String replacement)

3) replaceAll() 方法

replaceAll()方法用于将目标字符串中匹配某正则表达式的所有子字符串替换成新的字符串

replaceAll(String regex, String replacement)


推荐文档