简体   繁体   中英

How do I replace only strings that are not between two quotes in c#

For example I have string:

(one two tree "one" five "two" "two" "five" two "six" two six)

I want for the output to be:

(one 2 tree "one" five "two" "two" "five" 2 "six" 2 six)

string.replace("two", "2"), will replace all "two" in the string, and that is not what I'm looking for

Try Regex.Replace() + string.Format()

Substitutes the placeholder ( {0} ) with a string value ( two , here) and matches the input when the string value specified is preceded by a space or start of line and followed by a space or end of line.
The matches are replaced with another string ( "2" , here):

string input = "one two tree \"one\" five \"two\" \"two\" \"five\" two \"six\" two six";
string pattern = @"(?<=^|\s){0}(?=\s|$)";
string result = Regex.Replace(input, string.Format(pattern, "two"), "2");

result is:

one 2 tree "one" five "two" "two" "five" 2 "six" 2 six

You can create your own replace method like:

private void replace()
    {
        string str = "one two tree 'one' five 'two' 'two' 'five' two 'six' two six";
        string[] strArr = str.Split(' ');
        for(int i =0;i<strArr.Length;i++)
        {
            if(strArr[i]=="two")
            {
                strArr[i] = "2";
            }
        }
        str = string.Join(" ", strArr);
        return str;
    }

This code will split the string into array and check weather the indexed string is same or not if it include (") it will not consider it.

You can split the string by " this creates an array of strings, from which every string on an odd index would be enclosed by quots. So every string on an even index is not quoted and you can savely perform you replacement. Then just join them back together with " s between the substrings.

var str = "one two tree \"one\" five \"two\" \"two\" \"five\" two \"six\" two six";

var strs = str.Split('"');

for (int i = 0; i < strs.Length; i += 2) {
    strs[i] = strs[i].Replace("two", "2");
}

If you want to make it a bit more generic, in addition to other responses you could iterate over all elements and skip those that are wrapped in the " character. Something like:

var split = str.Split(' ');
foreach (var el in split) {
    if (el.StartsWith("\"") && el.EndsWith("\"")) {
        continue;
    }
    // do your replace here
}

Not a big difference but at least you have a bit cleaner code since now you can do whatever replace you want near the comment, with certainty that the element was not wrapped in quotes, whether it's replacing two with 2 or any other change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM