【问题标题】:Anyone know a good regex to remove extra whitespace? [duplicate]任何人都知道一个好的正则表达式来删除额外的空格? [复制]
【发布时间】:2011-02-28 00:08:43
【问题描述】:

可能重复:
Substitute multiple whitespace with single whitespace in Python

试图弄清楚如何编写一个给定字符串的正则表达式:

"hi     this       is a  test"

我可以把它变成

"hi this is a test"

空白被归一化为一个空格

有什么想法吗?非常感谢

【问题讨论】:

    标签: python regex


    【解决方案1】:
    import re    
    re.sub("\s+"," ",string)
    

    【讨论】:

      【解决方案2】:

      它需要是一个正则表达式吗?

      我只是用

      new_string = " ".join(re.split(s'\s+', old_string.strip()))
      

      【讨论】:

      • 你仍然使用正则表达式 ;)
      • 我以为我写出来的时候,实际上:)
      【解决方案3】:

      sed

       sed 's/[  ]\{2,\}/ /g'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-24
        • 2023-02-22
        • 1970-01-01
        相关资源
        最近更新 更多