One string I transferred from JSON to string as below:
"FIELDLIST": [ "Insurance Num", "Insurance PersonName", "InsurancePayDate", "InsuranceFee", "InsuranceInvType" ]
I am trying to strip the space and I hope the result is:
"FIELDLIST":["Insurance Num","Insurance PersonName","InsurancePayDate","InsuranceFee","InsuranceInvType"]
and I write the code in c# as follows:
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;
}
}
}
but it doesn't work at all, it seems I have to use Regex to replace,how can I use it??
Use Regular expression (\\s(?=")|\\s(?=\\])|\\s(?=\\[))+
Here is code:
string str = "\"FIELDLIST\": [ \"Insurance Num\", \"Insurance PersonName\", \"InsurancePayDate\", \"InsuranceFee\", \"InsuranceInvType\" ] ";
string result = System.Text.RegularExpressions.Regex.Replace(str, "(\\s(?=\")|\\s(?=\\])|\\s(?=\\[))+", string.Empty);
Just match the spaces which exists between two non-word characters and then replace the matched spaces with empty string.
@"(?<=\W)\s+(?=\W)"
Code:
string str = @"""FIELDLIST"": [ ""Insurance Num"", ""Insurance PersonName"", ""InsurancePayDate"", ""InsuranceFee"", ""InsuranceInvType"" ]";
string result = Regex.Replace(str, @"(?<=\W)\s+(?=\W)", "");
Console.WriteLine(result);
Output:
"FIELDLIST":["Insurance Num","Insurance PersonName","InsurancePayDate","InsuranceFee","InsuranceInvType"]
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.