繁体   English   中英

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

[英]How can I use Regex to replace this string

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

但它根本不起作用,似乎我必须使用Regex替换,我该如何使用它?

使用正则表达式(\\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"]

爱迪生

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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