好的正则表达,我需要以下
简单地说,这只是一个基本的句子整洁(关于逗号和空格)
我目前的解决方案是有效的,但我想知道是否有办法通过更智能的regex
表达式来减少看似冗余的步骤
当前解决方案
[TestCase(" , aaa,bbb ,, , ccc, ddd,, eee fff , , ggg , hhh ,", ExpectedResult = "aaa, bbb, ccc, ddd, eee fff, ggg, hhh")]
[TestCase(",, aaa,bbb ,, , ccc, ddd,, eee fff , , ggg , hhh ,, ", ExpectedResult = "aaa, bbb, ccc, ddd, eee fff, ggg, hhh")]
[TestCase(",, ,,", ExpectedResult = "")]
public string CleanSentence(string source)
{
var duplicateSpaces = new Regex(@"[ ]{2,}", RegexOptions.None);
var spacesBeforeCommas = new Regex(@"\s+(?=,)", RegexOptions.None);
var duplicateCommas = new Regex(@"[,]{2,}", RegexOptions.None);
var loneComma = new Regex(@",(?=[^\s])", RegexOptions.None);
var multiCommaAndSpace = new Regex(@"(, ){2,}", RegexOptions.None);
source = duplicateSpaces.Replace(source, " ");
source = duplicateCommas.Replace(source, ",");
source = spacesBeforeCommas.Replace(source, "");
source = loneComma.Replace(source, ", ");
source = multiCommaAndSpace.Replace(source, ", ");
//Trim the crud
source = source.Trim(',', ' ');
return source;
}
测试用例
var test1 = " , aaa,bbb ,, , ccc, ddd,, eee fff , , ggg , hhh ,"
var test2 = ",, aaa,bbb ,, , ccc, ddd,, eee fff , , ggg , hhh ,, "
var test3 = ",, ,,"
预期结果
var Result1 = "aaa, bbb, ccc, ddd, eee fff, ggg, hhh"
var Result2 = "aaa, bbb, ccc, ddd, eee fff, ggg, hhh"
var Result3 = ""
虽然我想知道是否有办法删除一些冗余步骤
注意:这是一个可量化的问题,即减少智能正则表达式所涉及的步骤
答案 0 :(得分:2)
I have another solution just by using only string
built-in function and a little Regex.Replace
.
public string CleanString(string rawString)
{
if (string.IsNullOrWhiteSpace(rawString)) return rawString;
rawString = Regex.Replace(rawString, @"\s+", " ");
rawString = Regex.Replace(rawString, @"(?<=,)\s+|\s+(?=,)", "");
return string.Join(", ", rawString.Trim().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).Trim();
}
答案 1 :(得分:0)
我建议如下:
\s+\b
\s
[,\s]*,
,
醇>
这也将删除每个字符串末尾的空格。
希望这有帮助。
答案 2 :(得分:0)
我设法从 John Woo
获得了一些灵感 source = Regex.Replace(source, "[ ]{2,}", " ");
source = Regex.Replace(source, "[, ]*,[, ]*", ", ");
return source.Trim(',', ' ');
对于任何能够制作2个正则表达式语句的人,我都会获得奖励 修剪
答案 3 :(得分:0)
似乎只是按空格分割,逗号就足够了:
public string CleanSentence(string source)
{
return string.Join(", ", (source ?? "").Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));
}