如何仅替换不在 c 中两个引号之间的字符串#

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

提问人:mohamed sherrif 提问时间:5/13/2020 最后编辑:Rekshinomohamed sherrif 更新时间:5/13/2020 访问量:288

问:

例如,我有字符串:

(一、二、树、一、五、二、二、五、二、六、二、六)

我希望输出为:

(一、2、树、“一”五、五、二、二“五”、2、“六”、2、6)

string.replace(“two”, “2”),将替换字符串中的所有“two”,这不是我要找的

C# 字符串 引号

评论

1赞 Emond 5/13/2020
string.replace(“二”, “2”)。替换(“\”2\“”, “\”two\“”)
0赞 Ackdari 5/13/2020
您可以拆分字符串,并且只对每个具有偶数索引的子字符串进行替换。并将它们连接在一起,并在它们之间""
0赞 InBetween 5/13/2020
@erno 从理论上讲,使用这样的字符串会失败:'one two 'one two' three...”。OP 似乎暗示这不是一个需要考虑的场景,但仍然值得指出。
0赞 mohamed sherrif 5/13/2020
感谢您的回答: string input = “one two tree \”one\“ five \”two\“ \”two\“ \”five\“ two \”six\“ two six”;字符串模式 = @“(?<=^|\s){0}(?=\s|$)”;string result = Regex.Replace(input, string.格式(pattern, “two”), “2”);解决了问题

答:

0赞 Hammad Asif 5/13/2020 #1

您可以创建自己的替换方法,例如:

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;
    }

此代码会将字符串拆分为数组并检查天气,索引字符串是否相同,如果它包含 (“),则不会考虑它。

评论

0赞 mohamed sherrif 5/13/2020
谢谢你的回答,我找到了解决方案。
0赞 Ackdari 5/13/2020 #2

您可以通过此方式拆分字符串,从而创建一个字符串数组,奇数索引上的每个字符串都将用引号括起来。因此,偶数索引上的每个字符串都没有引号,您可以节省地执行替换。然后只需在子字符串之间用 s 将它们重新连接在一起。""

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");
}

评论

0赞 mohamed sherrif 5/13/2020
谢谢你的回答,我找到了解决方案。
0赞 Rob1n 5/13/2020 #3

如果你想让它更通用一些,除了其他响应之外,你还可以遍历所有元素,并跳过那些包装在 “ 字符中的元素。像这样:

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

没有太大的区别,但至少你有更干净的代码,因为现在你可以在注释附近做任何你想做的替换,可以肯定的是,该元素没有被括起来,无论是用 2 替换 2 还是任何其他更改。

评论

0赞 mohamed sherrif 5/13/2020
谢谢你的回答,我找到了解决方案。
1赞 Jimi 5/13/2020 #4

试试 Regex.Replace() + string。格式()

将占位符 () 替换为字符串值 (, here),并在指定的字符串值前面有空格或行首,后跟空格或行尾时匹配输入。
匹配项将替换为另一个字符串(此处):
{0}two"2"

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");

结果是:

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