简体   繁体   中英

Java replace content which use whitespace as delimiter in a string(case insensitive)

First, consider the case sensitive. For example, str = "foo foo ,foo, .foo. foo foo" ; positions :1 2 3 4 5 6 str = "foo foo ,foo, .foo. foo foo" ; positions :1 2 3 4 5 6 .

As the second "foo" and the fifth "foo" use whitespace as delimiter, they will be replaced by "zoo" .

Then, the result = "foo zoo ,foo, .foo. zoo foo"

Second, consider the case insensitive, for example:

str = "foo Foo ,foo, .foo. Foo foo" ; positions :1  2  3  4  5  6

As the second "Foo" and the fifth "Foo" use whitespace as delimiter, they will be replaced by "zoo" in a case insensitive scenario.

Then, the result = "foo zoo ,foo, .foo. zoo foo"

I would like to use replaceALL() , but couldn't find regex can restrict delimiter on the content. Also, how to combine delimiter restriction with case insensitive restriction?

Thank you very much!

If I understood correctly:

    String t = "foo Foo ,foo, .foo. foo foo";
    t = t.replaceAll("(?i)(?<=\\s)(\\w+)(?=\\s)", "zoo");
    System.out.println(t); // foo zoo ,foo, .foo. zoo foo
        String str1 = "foo foo ,foo, .foo. foo foo" ;
        String str2 = "foo Foo ,foo, .foo. Foo foo" ; 
        str1 = str1.replaceAll("(?i) foo ", " zoo ");
        str2 = str2.replaceAll("(?i) foo ", " zoo ");
        System.out.println("str1: "+str1);
        System.out.println("str2: "+str2);

Using replaceAll its a good aproach. I think that you must look for regex, in this link for example.

This is an implementation that apply for your examples, but maybe you need to make some changes if you want something a bit different.

text = text.replaceAll("(?i) " + keyWord + " ", " zoo ");

In this case,

keyWord = "foo";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM