I want to replace a string in Java, but there are the following rules.

Do not replace abc.
Do not replace desk.
Replace a with x.
Replace c with x.
Replace d with x.

String str = "abcdefg desktop ac";
String replaced = "abcxefg desktop xx";<- str I want to replace like this

If i simply replace acd, you will also replace ac in abc and d in desk.

I think the following logic will work,
The string that should not be replaced is variable, and the end of the string must be determined.
I think the process becomes a little complicated.

for (int i = 0;i<str.length;i++) {
  // If str.substring(i, 3) is not abc and str.substring(i, 4) is not desk
  // If str.substring(i, 1) is a, c, d, replace

Is there any good regular expression or logic?

  • Answer # 1

    For the time being, I think it's good to implement the rules you wrote.
    If you do it, probably do this.

    1st stage

    (1) Do not replace abc.
    (2) Do not replace desk.

    First, replace it with another character in the regular expression.
    Depending on what you are replacing, let's say (1) [email protected] and (2) desk=#.
    In reality, you should replace it with a character that you can't type.

    Second stage

    Since abc and desk are already different characters, we simply replace them with regular expressions using the following rules.

    (3) Replace a with x.
    (4) Replace c with x.
    (5) Replace d with x.

    3rd stage

    Replace the one that was replaced in the first step.
    @ =>abc, # =>desk

  • Answer # 2

    public class Test1 {
        public static void main(String[] args) {
            String str1 = "abcdefg desktop ac";
            String array1[] = str1.split("(?<=(abc|desk))|(?=(abc|desk))");

    Disassemble into an array like this and execute replacement only when each element is not abc or desk. How about putting them all together and turning them back into a single string?

  • Answer # 3

    If you think that "a without bc following", "c without ab before" or "d without esk after" is replaced with x,Negative lookahead, negative lookbehindIt is possible by using.

    String str = "abcdefg desktop ac";
    String replaced = str.replaceAll("(a(?!bc)|c(?<!abc)|d(?!esk))", "x");