2013-07-07 51 views
1

我在寫一個動態代碼編寫器,並且正在編寫一個寫入XML文檔的函數。一切都很好,除了格式化文檔的函數不期望地添加到最後,我還需要它打破標點符號。將行附加到Replace末尾的正則表達式()

當前格式化功能:

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

嘗試使用該正則表達式:

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

\b確保字不是在中間分開,$提供的最後一行。

+0

這也避免了將'Nullable:'分割爲'Nullable \ r \ n:'這樣的東西,但是如果還有更多類似的東西,請將它們添加到字符類中的負向預覽中。 – Jerry

+0

謝謝,但這實際上並沒有分割輸入,並且仍然在最後添加2行。 – IamIC

+0

var regex = new Regex(@「\ b。{0,」+ length.ToString()+「}(?:(?!:)\ b | $)」); return regex.Replace(xmlLine,「$ 0 \ r \ n」+ string.Empty.PadRight(spacing)+「///」); – IamIC