Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用正则表达式替换此字符串_C#_Regex_Replace - Fatal编程技术网

C# 如何使用正则表达式替换此字符串

C# 如何使用正则表达式替换此字符串,c#,regex,replace,C#,Regex,Replace,我将一个字符串从JSON传输到字符串,如下所示: "FIELDLIST": [ "Insurance Num", "Insurance PersonName", "InsurancePayDate", "InsuranceFee", "InsuranceInvType" ] 我试图剥离空间,我希望结果是: "FIELDLIST":["Insurance Num","Insurance PersonName","InsurancePayDa

我将一个字符串从JSON传输到字符串,如下所示:

"FIELDLIST": [      "Insurance Num",      "Insurance PersonName",      "InsurancePayDate",      "InsuranceFee",      "InsuranceInvType"    ]
我试图剥离空间,我希望结果是:

"FIELDLIST":["Insurance Num","Insurance PersonName","InsurancePayDate","InsuranceFee","InsuranceInvType"]
我用c编写代码如下:

string[] rearrange_sign = { ",", "[", "]", "{", "}", ":" };
string rtnStr = _prepareStr;

for (int i = 0; i < rearrange_sign.Length; i++)
{
    while (true)
    {
        rtnStr = rtnStr.Replace(@rearrange_sign[i] + " ", rearrange_sign[i]);
        rtnStr = rtnStr.Replace(" " + @rearrange_sign[i], rearrange_sign[i]);
        if (rtnStr.IndexOf(@rearrange_sign[i] + " ").Equals(-1) && rtnStr.IndexOf(" " + @rearrange_sign[i]).Equals(-1))
        {
            break;
        }
    }
}
但它根本不起作用,似乎我必须使用正则表达式来替换,我如何使用它???

使用正则表达式\s?=\s?=\]\s=\[+

以下是代码:

string str = "\"FIELDLIST\": [ \"Insurance Num\", \"Insurance PersonName\", \"InsurancePayDate\", \"InsuranceFee\", \"InsuranceInvType\" ] ";
string result = System.Text.RegularExpressions.Regex.Replace(str, "(\\s(?=\")|\\s(?=\\])|\\s(?=\\[))+", string.Empty);

只需匹配两个非单词字符之间的空格,然后用空字符串替换匹配的空格

@"(?<=\W)\s+(?=\W)"
string str = @"""FIELDLIST"": [      ""Insurance Num"",      ""Insurance PersonName"",      ""InsurancePayDate"",      ""InsuranceFee"",      ""InsuranceInvType""    ]";
string result = Regex.Replace(str, @"(?<=\W)\s+(?=\W)", "");
Console.WriteLine(result);
"FIELDLIST":["Insurance Num","Insurance PersonName","InsurancePayDate","InsuranceFee","InsuranceInvType"]