【问题标题】:Reg ex remove non alpha characters keeping spaces正则表达式删除保留空格的非字母字符
【发布时间】:2016-10-18 09:52:51
【问题描述】:

我编写了一个简单的函数,它去除所有非字母字符组成的字符串,保留空格。

目前它依赖于使用两个正则表达式。但是,为了简洁起见,我想将这两个 reg exs 简化为一个。这可能吗?

import re

def junk_to_alpha(s):
  reg = r"[^A-Za-z]"
  p = re.compile(reg)
  s = re.sub(p, " ", s)
  p = re.compile(r"\s+")
  s = re.sub(p, " ", s)
  return s

print junk_to_alpha("Spoons! 12? \/@# ,.1 12 Yeah? {[]}")

# Spoons Yeah

【问题讨论】:

    标签: python regex string python-2.7


    【解决方案1】:

    您可以将[^a-zA-Z]+\s* 括起来:

    import re
    
    def junk_to_alpha(s):
      s = re.sub(r"\s*[^A-Za-z]+\s*", " ", s)
      return s
    
    print junk_to_alpha("Spoons! 12? \/@# ,.1 12 Yeah? {[]}")
    

    online Python demo

    图案详情:

    • \s* - 零个或多个空格
    • [^A-Za-z]+ - 1 个或多个除 ASCII 字母以外的字符
    • \s* - 见上文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-15
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多