简体   繁体   中英

Java - Case insensitive split WITH VARIABLE splitting string

program test so I have a program that will be given two strings as arguments: base and remove. It has to take out remove from base. I am using the split method to remove the second string from the first. However, the case on the chars of the second string should not matter, while the case of the first string must be preserved. I found a lot of ways to do this when you define the remove string in the program as a String literal: I can use ?i for example, but because remove is coming in as an argument and not a literal that I am defining in the program, this isn't working. Please check my attached picture so that you can see exactly where this is failing. Appreciate the help.

public String withoutString(String base, String remove) {

      String array[] = base.split(remove);
      String result = "";
        for(int i = 0; i<array.length;i++)
          result+= array[i];

      return result;
    }

Use a regex pattern with CASE_INSENSITIVE and LITERAL flags:

return Pattern.compile(remove, Pattern.CASE_INSENSITIVE | Pattern.LITERAL)
        .matcher(base).replaceAll("");

String.replaceAll() method accepts regex you can use directly like:

return base.replaceAll("(?i)(" + remove +")[\\s]*", "")

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