Ziad-Mid
Ziad-Mid

Reputation: 13

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

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"

Upvotes: 1

Views: 823

Answers (1)

41686d6564
41686d6564

Reputation: 19661

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.

Upvotes: 1

Related Questions