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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With