正则表达式,用于查找完整文本和插入空间

时间:2011-01-20 15:49:35

标签: c# asp.net-mvc regex

我正在建立一个论坛,现在它正处于测试阶段。用户已经开始利用某些东西,比如发布长串的文本,没有空间会拉伸屏幕并破坏一些样式。我刚开始使用此代码,它工作正常。

        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个字符插入一个不间断的非链接文本空格。

有什么建议吗?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

全局

"([^ ]{150})替换为"\1 "(根据您的正则表达式修改)

相关问题