[英]Using regex.replace() to add to ", and "to the third to last comma in a string
I have a two scenarios which occur in my code:我的代码中有两种情况:
My goal is to properly add the and to the last item in the comma separated list to follow standard English practices.我的目标是将 and 正确添加到逗号分隔列表中的最后一项,以遵循标准的英语惯例。 The designation commas for the last item throw off my Regex expression I was using to add that last and in replacement of the comma.
最后一项的指定逗号脱离了我用来添加最后一项并替换逗号的正则表达式。
My code:我的代码:
if(str1.EndsWith(", CPA, CFA"))
{
//need to figure out
}
else
{
Regex.Replace(str1, ", ([^,]+)$", " and $1");
}
You can use the following code without using Regex
您可以在不使用
Regex
的情况下使用以下代码
//string input = "John, Jan, Joe, CPA, CFA";
string input = "John, Jan, Joe";
var result = input.Select((b, i) => b.Equals(',') ? i : -1).Where(i => i != -1).ToList();
if(input.EndsWith(", CFA"))
input=input.Replace(input.Substring(0,result[result.Count()-3] +2), input.Substring(0, result[result.Count()-3]+2) + "and ");
else
input = input.Replace(input.Substring(0, result[result.Count()-1] +1), input.Substring(0, result[result.Count()-1]) + " and ");
Console.WriteLine(input);
if string input = "John, Jan, Joe, CPA, CFA"
:如果
string input = "John, Jan, Joe, CPA, CFA"
:
result: "John, Jan, and Joe, CPA, CFA" (Apparently, you have added an extra comma)
结果:“John, Jan, and Joe, CPA, CFA”(显然,您添加了一个额外的逗号)
if string input = "John, Jan, Joe"
;如果
string input = "John, Jan, Joe"
;
result: John, Jan and Joe
结果:约翰、简和乔
You might use a pattern with 2 capture groups capturing the first comma and match the second comma您可以使用带有 2 个捕获组的模式捕获第一个逗号并匹配第二个逗号
The the replacement use the 2 groups $1 and $2
替换使用 2 组
$1 and $2
([^\s,]+),\s*([^\s,]+(?:, CPA, CFA)?)$
The pattern matches:模式匹配:
([^\s,]+)
Capture group 1 , match 1+ non whitespace chars and a comma ([^\s,]+)
捕获组 1 ,匹配 1+ 个非空白字符和一个逗号
,\s*
Match a comma and optional whitespace chars ,\s*
匹配逗号和可选的空白字符
(
Capture group 2 (
捕获组 2
[^\s,]+
Match 1+ chars other than a whitespace char or comma [^\s,]+
匹配除空白字符或逗号以外的 1+ 个字符(?:, CPA, CFA)?
Optionally match , CPA, CFA
, CPA, CFA
)
Close group 2 )
关闭第 2 组
$
End of string $
字符串结束
Regex demo |正则表达式演示| C# demo
C#演示
Example例子
string pattern = @"([^\s,]+),\s*([^\s,]+(?:, CPA, CFA)?)$";
string input = "John, Jan, Joe\nJohn, Jan, Joe, CPA, CFA\njake, jan, joe, john, jessie, jack, jones";
Console.WriteLine(Regex.Replace(input, pattern, @"$1 and $2", RegexOptions.Multiline));
Output Output
John, Jan and Joe
John, Jan and Joe, CPA, CFA
jake, jan, joe, john, jessie, jack and jones
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.