JAVA replaceAll regex和replacement转义

本文详细介绍了Java中字符串替换方法replaceAll的使用技巧,包括regex和replacement的转义规则,以及如何利用Matcher.quoteReplacement和Pattern.quote确保转义的正确性。
部署运行你感兴趣的模型镜像

JAVA replaceAll regex和replacement转义

replacement转义

有下面这段代码:

public static void main(String[] args){
    System.out.println("abcdef".replaceAll("abc","$"));//1
    System.out.println("abcdef".replaceAll("abc", "\\"));//2
}

咋一看没毛病,但是运行会报错:

1:Exception in thread "main" java.lang.IllegalArgumentException: Illegal group reference: group index is missing
2:Exception in thread "main" java.lang.IllegalArgumentException: character to be escaped is missing

因为\$replacement中的特殊字符,前者用来转义,后者用来匹配组并使用$n来引用第n个组。它们的正确使用方法如下:

System.out.println("abcdef".replaceAll("abc", "\\\\"));// \def
System.out.println("abcdef".replaceAll("abc", "\\$"));// $def
System.out.println("www.baidu.com".replaceAll("(.*)\\.(baidu)\\.(.*)", "https://$1.google.$3"));// https://www.google.com

可以看出这两个特殊字符的作用了,所以如果replacement里面包含有这两个特殊字符,却没有按照需要的规则来匹配,就会报错。除了直接使用\转义以外,还有一种方法在不知道replacement中是否包含特殊字符是特别有用:

public static void main(String[] args){
    System.out.println(replaceAll("abcdef","abc", "\\"));
    System.out.println(replaceAll("abcdef","abc", "$"));
}

public static String replaceAll(String s,String regex,String replacement){
    return s.replaceAll(regex,Matcher.quoteReplacement(replacement));
}

使用Matcher.quoteReplacement(replacement)就能将replacement中的所有特殊字符转义,是一种非常保险的方法,Matcher.quoteReplacement()就是一个转义的操作:

/**
 * Returns a literal replacement <code>String</code> for the specified
 * <code>String</code>.
 *
 * This method produces a <code>String</code> that will work
 * as a literal replacement <code>s</code> in the
 * <code>appendReplacement</code> method of the {@link Matcher} class.
 * The <code>String</code> produced will match the sequence of characters
 * in <code>s</code> treated as a literal sequence. Slashes ('\') and
 * dollar signs ('$') will be given no special meaning.
 *
 * @param  s The string to be literalized
 * @return  A literal string replacement
 * @since 1.5
 */
public static String quoteReplacement(String s) {
    if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
        return s;
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<s.length(); i++) {
        char c = s.charAt(i);
        if (c == '\\' || c == '$') {
            sb.append('\\');
        }
        sb.append(c);
    }
    return sb.toString();
}

regex转义

replacement类似的,如果regex中有字符需要转义,也可主动加\来转义,但是在不确定regex中是否有特殊字符时,可能就会出错:

public static void main(String[] args){
    System.out.println(replaceAll("My name is ${name}","${name}", "Hanmeimei"));
}

public static String replaceAll(String s,String regex,String replacement){
    return s.replaceAll(regex,Matcher.quoteReplacement(replacement));
}
Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 0
${name}
^

在确定regex中不包含正则表达式的时候,可以使用Pattern.quote()来转义:

public static void main(String[] args){
    System.out.println(replaceAll("My name is ${name}","${name}", "Hanmeimei"));//My name is Hanmeimei
}

public static String replaceAll(String s,String regex,String replacement){
    return s.replaceAll(Pattern.quote(regex),Matcher.quoteReplacement(replacement));
}

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值