我从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来替换,我该如何使用?
答案 0 :(得分:0)
使用正则表达式(\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);
答案 1 :(得分:0)
只匹配两个非单词字符之间存在的空格,然后用空字符串替换匹配的空格。
@"(?<=\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"]