You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

字符串搜索转换与API输入格式化代码重构需求

重构HOS字符串格式化代码的优化方案

你当前的代码已经实现了基本功能,但直接用+ " "的空值防护确实不够优雅,还可能导致多余空格的问题。下面是重构后的代码,兼顾可读性、健壮性和需求合规性:

重构后的完整代码

[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)
{
    // 定义正则匹配规则,单独处理每个片段的匹配结果
    var countryMatch = Regex.Match(input, @"\b(USA|CAN|MEX)\b");
    var dayHourMatch = Regex.Match(input, @"\d{1,2}\/\d{1,3}");
    var hrsMatch = Regex.Match(input, @"\bhrs\b");
    var dateMatch = Regex.Match(input, @"\(([a-zA-Z]+\s{1}[0-9]{4})\)");

    // 提取各部分内容,空值处理更严谨
    string country = countryMatch.Success ? countryMatch.Value : string.Empty;
    string dayHourPart = dayHourMatch.Success ? dayHourMatch.Value : string.Empty;
    string hrsSegment = hrsMatch.Success ? "hrs." : string.Empty; // 直接确保带句点,符合要求
    string dateSegment = dateMatch.Success ? dateMatch.Value : string.Empty;

    // 提取标题:移除已匹配的部分,清理多余空格
    string title = input;
    if (countryMatch.Success) title = title.Replace(countryMatch.Value, string.Empty);
    if (dayHourMatch.Success) title = title.Replace(dayHourMatch.Value, string.Empty);
    if (hrsMatch.Success) title = title.Replace(hrsMatch.Value, string.Empty);
    if (dateMatch.Success) title = title.Replace(dateMatch.Value, string.Empty);
    title = Regex.Replace(title, @"\s+", " ").Trim(); // 合并多余空格并修剪首尾

    // 按目标格式拼接,仅当内容非空时添加对应部分
    var outputParts = new List<string>();
    if (!string.IsNullOrEmpty(country)) outputParts.Add(country);
    if (!string.IsNullOrEmpty(dayHourPart)) outputParts.Add(dayHourPart);
    if (!string.IsNullOrEmpty(title)) outputParts.Add(title);
    if (!string.IsNullOrEmpty(hrsSegment)) outputParts.Add(hrsSegment);
    if (!string.IsNullOrEmpty(dateSegment)) outputParts.Add(dateSegment);

    return string.Join(" ", outputParts);
}

关键优化点说明

  • 严谨的空值与空格控制:
    抛弃了+ " "的偷懒写法,改用列表收集非空的内容片段,最后用单个空格拼接,彻底避免了多余空格的问题。
  • 强制合规的格式处理:
    直接将匹配到的hrs转换为hrs.,确保始终符合服务器要求的句点结尾规范;日期片段保持原括号格式,自动放在最后。
  • 更可靠的标题提取:
    替换时仅移除精确匹配到的内容,最后用正则清理冗余空格,避免原字符串中多空格导致的标题格式混乱。
  • 代码可维护性增强:
    变量名更贴合实际含义,逻辑拆分清晰,后续要修改规则(比如新增国家代码、调整日期格式)时更容易迭代。

内容的提问来源于stack exchange,提问作者Dylan Godfrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:48:33