2011-01-20 74 views
4

我正在構建一個論壇,它現在處於測試階段。用戶已經開始利用某些東西,比如張貼長文本的字符串,沒有空格將會拉長屏幕並破壞一些樣式。我剛開始使用這個代碼,它工作正常。正則表達式查找完整文本並插入空間

 int charIndex = 0; 
     int noSpaceCount = 0; 
     foreach (char c in text.ToCharArray()) 
     { 
      if (c != ' ') 
       noSpaceCount++; 
      else 
       noSpaceCount = 0; 

      if (noSpaceCount > 150) 
      { 
       text = text.Insert(charIndex, " "); 
       noSpaceCount = 0; 
      } 
      charIndex++; 
     } 

此代碼有效,但如果可能的話我更喜歡正則表達式。問題是,我將使用正則表達式來識別鏈接,並且我不想用空格來打破長鏈接,因爲鏈接顯示文本的縮寫將修復這些鏈接。所以我不想在標識爲URL的文本中插入一個空格,但是我希望每150個字符的非連續文本中插入一個空格。

有什麼建議嗎?

+1

這似乎是一個非常糟糕的解決方案,以固定的佈局問題更換"([^ ]{150})「與"\1 "全球。你不能添加自動換行? – alexn 2011-01-20 15:54:32

+0

自動換行,或'overflow:hidden`。 – Thomas 2011-01-20 15:55:23

回答

4

這非常複雜。感謝Eric和他的同事們的偉大的.NET正則表達式庫。

resultString = Regex.Replace(subjectString, 
    @"(?<=  # Assert that the current position follows... 
    \s  # a whitespace character 
    |   # or 
    ^  # the start of the string 
    |   # or 
    \G  # the end of the previous match. 
    )   # End of lookbehind assertion 
    (?!(?:ht|f)tps?://|www\.) # Assert that we're not at the start of a URL. 
    (\S{150}) # Match 150 characters, capture them.", 
    "$1 ", RegexOptions.IgnorePatternWhitespace); 
0

(根據你的正則表達式的味道修改)