【问题标题】:Need a Regular Expression that replaces all duplicate whitespace -next to each other- with a single whitepsace需要一个正则表达式,用一个空格替换所有重复的空格-彼此相邻-
【发布时间】:2011-07-10 02:21:13
【问题描述】:

我有一个简单的脚本(它使用 RegEx),它清理源字符串以仅留下 alpha-numeric-and-whitespace 个字符。

有时,我会得到一些相邻的空白字符。

例如。

source: abc def ghi 
result: abc def ghi

source: a*bc D*f
result: abc df

source: a*bc *** def
result: abc  def  <-- notice the two spaces in there
expected result: abc def  <-- notice one space, here.

所以我希望一些正则表达式可以在某些源字符串中查找 2+ 个相邻的空格,并将其替换为单个空格字符

干杯:)

【问题讨论】:

标签: regex


【解决方案1】:

只需使用\s\s+作为要匹配的字符串,并用一个空格作为替换。

【讨论】:

    【解决方案2】:

    在 C# 中,这将是:

    Regex regex = new Regex("\\s\\s+");
    string output = regex.Replace(input, " ");
    

    【讨论】:

      【解决方案3】:

      这是一个快速的 JavaScript 函数。这会处理所有空格,而不仅仅是空格。

      function stripExtraSpaces(text)
      {
         var exp = new RegExp("[\\s]+","g");
         return text.replace(exp," ");
      }
      

      【讨论】:

        猜你喜欢
        • 2015-09-16
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 2013-09-21
        • 1970-01-01
        • 2011-11-18
        • 2017-10-22
        • 1970-01-01
        相关资源
        最近更新 更多