正则表达式将行附加到Replace()的末尾

时间:2013-07-07 11:50:40

标签: c# regex

我正在编写动态代码编写器,而我正在编写一个编写XML文档的函数。一切都很好,除了格式化文档的功能不合理地添加到最后,我还需要它来打破标点符号。

当前格式化功能:

public static String FormatForXmlDocumentation(String xmlLine, Int32 spacing, 
  Int32 length = 120)
{
    if (!string.IsNullOrEmpty(xmlLine))
    {
        var regex = new Regex(@".{0," + length.ToString() + "}", RegexOptions.Multiline);
        return regex.Replace(xmlLine, "$0\r\n" + string.Empty.PadRight(spacing) + "/// ");
    }

    return null;
}

测试代码(“!”表示结束):

Console.WriteLine(RenderForCode.FormatForXmlDocumentation(
@"Data info: Type: <see cref=""System.Nullable`1[System.Double]""/>; Nullable: false; Default: 101.23d; Low: 100d; High: 200d", 4, 40
) + "!");

当前输出:

Data info: Type: <see cref="System.Nulla
    /// ble`1[System.Double]"/>; Nullable: false
    /// ; Default: 101.23d; Low: 100d; High: 200
    /// d
    /// 
    /// !

期望的输出:

Data info: Type: <see cref="System.
    /// Nullable`1[System.Double]"/>; Nullable: 
    /// false; Default: 101.23d; Low: 100d; 
    /// High: 200d!

请注意,调用函数将处理第一行的前缀。

1 个答案:

答案 0 :(得分:1)

尝试使用正则表达式:

@"\b.{0," + length.ToString() + @"}(?:(?!:)\b|$)"

\b确保单词不会在中间分割,$提供最后一行。

相关问题