user3520434
user3520434

Reputation:

C# - Regex replace if not inside of quotes

Let's take this block of code:

string Val = "I like foo, baz and bar, they where before \"foo, baz and bar\"";

string[] first = {
    "foo",
    "baz",
    "bar"
};

string[] second = {
    "java",
    "php",
    "ruby"
};

Look that inside my Val string I have a text, I want to replace only the part which isn't inside of the quotes (\"), but if I do

Val = Regex.Replace(Val, first, second);

It just gives me

I like java, php and ruby, they where before "java, php and ruby"

While I expect

I like java, php and ruby, they where before "foo, baz and bar"

Can someone help to solve this problem? I didn't find any documentation explaining it.

Upvotes: 2

Views: 404

Answers (1)

Guffa
Guffa

Reputation: 700910

You can split on quotation marks and do the replace on every other string, then put the strings together:

string[] parts = Val.Split('"');
for (int i = 0; i < parts.Length; i += 2) {
  parts[i] = Regex.Replace(parts[i], first, second);
}
Val = String.Join("\"", parts);

Upvotes: 4

Related Questions