2011-01-20 67 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

(根据你的正则表达式的味道修改)