我有一个 API 接受在进入服务器之前需要正确格式化的字符串。
进入服务器的格式如下
"{Country ABR} {Day/Hour} {State ABR} {Title} {hrs.} ({Month Year}.)"
客户可能发送的几种可能性:
"US Construction 7/70 hrs."
"IA Private hrs US.
"OIL US 8/70 hrs (Dec 2014).
转换用户输入后的几个有效示例是:
"US 7/70 MI Construction hrs."
"US IA Private hrs."
"US OIL 8/70 hrs. (Dec 2014)"
转换器将输入排列成正确的顺序。hrs 总是以句点结尾并在句子外重新排列 ({Month Year}),如图所示。
到目前为止我有
[TestMethod]
public void TestMethod1()
{
var toConvert = "USA Construction 70/700 (Dec 2014) hrs";
var converted = ConvertHOSRules(toConvert);
Assert.AreEqual(converted, "USA 70/700 Construction hrs.(Dec 2014)");
}
private string ConvertHOSRules(string input)
{
//todo refactor
string output = "";
string country = Regex.Match(input, @"\b(USA|CAN|MEX)\b").Value +" ";
string dateHours = Regex.Match(input,@"\d{1,2}\/\d{1,3}").Value + " ";
string hrs = Regex.Match(input, @"\b(hrs)\b").Value ;
var date = Regex.Match(input, @"\(([a-zA-Z]+\s{1}[0-9]{4})\)").Value + " ";
string title = input.Replace(country, "").Replace(date, "").Replace(dateHours, "").Replace(hrs, "");
output = $"{country} {dateHours} {title} {hrs}.{date}";
return output;
}
这是通过我需要重构.. +“”就像懒惰程序员的空守卫