Home > OS >  Java regex, replace certain characters except if it matches a pattern
Java regex, replace certain characters except if it matches a pattern

Time:05-05

I have this string "person","hobby","key" and I want to remove " " for all words except for key so the output will be person,hobby,"key"

String str = "\"person\",\"hobby\",\"key\"";
System.out.println(str "\n");

str=str.replaceAll("/*regex*/","");

System.out.println(str); //person,hobby,"key"

CodePudding user response:

You may use the following pattern:

\"(?!key\")(. ?)\"

And replace with $1

Details:

  • \" - Match a double quotation mark character.

  • (?!key\") - Negative Lookahead (not followed by the word "key" and another double quotation mark).

  • (. ?) - Match one or more characters (lazy) and capture them in group 1.

  • \" - Match another double quotation mark character.

  • Substitution: $1 - back reference to whatever was matched in group 1.

Regex demo.

Here's a full example:

String str = "\"person\",\"hobby\",\"key\"";
String pattern = "\"(?!key\")(. ?)\"";
String result = str.replaceAll(pattern, "$1");

System.out.println(result);  // person,hobby,"key"

Try it online.

  • Related