1

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"

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

and for key(type) , I tried this pattern "(?!key(.*)")(.+?)" but didn't work I get this output person,name,"key:VID(string), hobby" , how can I fix it ?
@Ziad-Mid I'm not sure I understand. If you have "key:something" instead of "key", the quotes will be removed. Isn't that what you want? See this demo.
no I asked if we do the same thing but instead of key we use key(type) for example in this String "person","name","key(string)","hobby" I want the output as person,name,"key(string)",hobby
@Ziad-Mid Is it always "key(something" or do you want it to work for any string starting with "key"? Perhaps \"(?!key)(.+?)\" or \"(?!key\b)(.+?)\" is what you're after?
it is always key(something) I tried those you sent but they don't work it's same output as before ` person,name,"key(string), hobby" `
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.