[英]How can I use Regex to replace this string
One string I transferred from JSON to string as below: 我从JSON转移到一个字符串,如下所示:
"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: 我用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;
}
}
}
but it doesn't work at all, it seems I have to use Regex to replace,how can I use it?? 但它根本不起作用,似乎我必须使用Regex替换,我该如何使用它?
Use Regular expression (\\s(?=")|\\s(?=\\])|\\s(?=\\[))+
使用正则表达式
(\\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"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.