Yoland Gao
Yoland Gao

Reputation: 437

How to Replace Words Outside Of Quotes

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!

Upvotes: 6

Views: 762

Answers (5)

anubhava
anubhava

Reputation: 785058

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

Upvotes: 6

Compass
Compass

Reputation: 5937

There's also an option to do this without a more complicated regex if you're looking for a more iterative solution, if you're so inclined. You can split on " and replace even-numbered indexes and then rebuild the string.

    String input = "\"unique\" unique unique \"unique\" \"unique\" \"unique\" \"unique\" unique \"unique unique\" unique unique \"";
    System.out.println(input);
    String[] split = input.split("\"");
    for (int i = 0; i < split.length; i = i + 2) {
        split[i] = split[i].replaceAll("unique", "potato");
    }
    String output = "";
    for (String s : split) {
        output += s + "\"";
    }
    System.out.println(output);

Output:

"unique" unique unique "unique" "unique" "unique" "unique" unique "unique unique" unique unique "
"unique" potato potato "unique" "unique" "unique" "unique" potato "unique unique" potato potato "

Upvotes: 0

Bikerdan
Bikerdan

Reputation: 99

Try matching the word with whitespace after it.

/Apple\s/

Then replace with Pie with the same whitespace after it.

Upvotes: 0

Daniel Kaplan
Daniel Kaplan

Reputation: 67320

This works for your test:

package mavensandbox;


import static junit.framework.TestCase.assertEquals;

public class Test {

    @org.junit.Test
    public void testName() throws Exception {
        String input = "Apple(\"Apple\")";
        String output = replaceThoseWithoutQuotes("Apple", "Pie", input);
        assertEquals("Pie(\"Apple\")", output);
    }

    private String replaceThoseWithoutQuotes(String replace, String with, String input) {
        return input.replaceAll("(?<!\")" + replace + "(?!\")", with);
    }
}

I'm using what's called a negative lookahead and a negative lookbehind. It finds matches that don't have a " in front or behind of it. Does that work for you?

Upvotes: 0

m0bi5
m0bi5

Reputation: 9452

I assume this is what you want:

String str = "Apple \"Apple\"";
String replace = str.replaceAll("(?<!\")Apple(?!\")", "Pie");

Here is the working:https://regex101.com/r/kP0oV1/2

Upvotes: 0

Related Questions