How to do a case-insensitive string replacement

倖福魔咒の 提交于 2019-12-05 06:16:59

Could use a regular expression. Just add (?i) before your string to ignore case.

So for example:

multiword.getString().replaceAll ( "(?i)radha", "sai");

rslj

You can "(?i)" pattern in front of a string to ignore the case.

public class StringReplace {

    public static void main(String[] args) {
        System.out.println(replaceString("This is a FISH", "IS"));
    }

    public static String replaceString(String first, String second) {
          return first.replaceAll("(?i)"+ second, "");
    }
}

The code above will return "Th a FH".

Use StringUtils by apache commons lang3 - v3.5 or later (so you don't have to worry about regular expression parsing):

StringUtils.replaceIgnoreCase(text, searchString, replacement);

or:

StringUtils.replaceOnceIgnoreCase(text, searchString, replacement);

If you use maven, add this dependency (I'm using version 3.6):

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.6</version>
</dependency>

You could use equalsIgnoreCase(string) method found in String class for your purpose.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!