如何在 Java 中替换不区分大小写的文字子字符串 [英] How to replace case-insensitive literal substrings in Java

查看:34
本文介绍了如何在 Java 中替换不区分大小写的文字子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在String中使用replace(CharSequence target, CharSequence replacement)方法,如何让目标不区分大小写?

Using the method replace(CharSequence target, CharSequence replacement) in String, how can I make the target case-insensitive?

例如,它现在的工作方式:

For example, the way it works right now:

String target = "FooBar";
target.replace("Foo", "") // would return "Bar"

String target = "fooBar";
target.replace("Foo", "") // would return "fooBar"

我怎样才能让替换(或者如果有更合适的方法)不区分大小写,以便两个示例都返回Bar"?

How can I make it so replace (or if there is a more suitable method) is case-insensitive so that both examples return "Bar"?

推荐答案

String target = "FOOBar";
target = target.replaceAll("(?i)foo", "");
System.out.println(target);

输出:

Bar

值得一提的是,replaceAll 将第一个参数视为正则表达式模式,这可能会导致意外结果.要解决此问题,还可以使用 Pattern.quote 如评论中所建议.

It's worth mentioning that replaceAll treats the first argument as a regex pattern, which can cause unexpected results. To solve this, also use Pattern.quote as suggested in the comments.

这篇关于如何在 Java 中替换不区分大小写的文字子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆