【问题标题】:Regular expression to find unbroken text and insert space正则表达式查找完整的文本并插入空格
【发布时间】:2011-01-20 15:49:35
【问题描述】:

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

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

有什么建议吗?

【问题讨论】:

  • 这似乎是解决布局问题的一个非常糟糕的解决方案。不能添加自动换行吗?
  • 自动换行,或overflow: hidden
  • 自动换行仅适用于静态大小的元素。它不适用于允许占据屏幕宽度的 div。它只会拉伸该 div 以适应内容。
  • 如何识别 URL?它会以http(s)/ftp(s):// 开头还是包裹在[url=...] 或...?
  • 理想情况下,它应该以 http(s)/ftp(s):// 或 www 开头。

标签: c# asp.net-mvc regex


【解决方案1】:

这非常复杂。感谢 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);

【讨论】:

  • 谢谢!现在测试一下。
  • 哇哦!我非常尊重你的正则表达式大师。我希望我能接受这个答案两次。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    相关资源
    最近更新 更多