Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Replace Words Outside Of Quotes

Tags:

java

string

regex

I would like to replace strings outside of quotes using str.replaceAll in Java but to leave words inside quotes untouched

If I replaced Apple with Pie:

Input: Apple "Apple Apple Apple"
Desired Output: Pie "Apple Apple Apple"

Note the words inside quotes were untouched

How would this be done? All help Appreciated!

like image 884
Yoland Gao Avatar asked Feb 27 '15 18:02

Yoland Gao


People also ask

How do you replace a word in a quote?

Words can be added or changed to a quote by using brackets. Changes can be used to correct tense or to add necessary information. Brackets can also be used to make the pronouns in a quote consistent. However, brackets should not be used to change the meaning of the quote.

What do you do when you remove a word from a quote?

If you omit a word or words from a quotation, you should indicate the deleted word or words by using ellipses, which are three periods ( . . . ) preceded and followed by a space.


1 Answers

Search for Apple using lookaheads to make sure it is not surrounded by quotes:

(?=(([^"]*"){2})*[^"]*$)Apple

And replace by:

Pie

RegEx Demo


Update:

Based on comments below you can use:

Code:

String str = "Apple \"Apple\"";
String repl = str.replaceAll("(?=(([^\"]*\"){2})*[^\"]*$)Apple", "Pie");
//=> Pie "Apple" "Another Apple Apple Apple" Pie
like image 81
anubhava Avatar answered Oct 08 '22 17:10

anubhava