【问题标题】:Extracting only characters from list items REGEX仅从列表项 REGEX 中提取字符
【发布时间】:2021-08-12 16:40:27
【问题描述】:

我正在练习正则表达式,我想从这个列表中只提取字符

text=['aQx12', 'aub 6 5']

我想忽略数字和空格,只保留字母。想要的输出如下

text=['aQx', 'aub']

我尝试了下面的代码,但它不能正常工作

import re 

text=['aQx12', 'aub 6 5']

r = re.compile("\D")
newlist = list(filter(r.match, text))

print(newlist)

谁能告诉我我需要解决什么问题

【问题讨论】:

  • 你可以试试这个:newlist = [j for t in text for j in re.findall("[a-zA-Z]+",t) ]
  • \D 应该是[\D\S]
  • @Sujay 谢谢。你的回答奏效了。
  • 你甚至不需要正则表达式。你检查过my answer吗?

标签: python regex list


【解决方案1】:

您正在测试整个字符串,而不是单个字符。您需要过滤字符串中的字符。

另外,\D 匹配任何不是数字的东西,因此它会在结果中包含空格。您只想匹配字母,即[a-z]

r = re.compile(r'[a-z]', re.I)
newlist = ["".join(filter(r.match, s)) for s in text]

【讨论】:

    【解决方案2】:

    您可以使用re.findall 然后加入比赛,而不是使用re.matchfilter,也可以使用[a-zA-Z] 来仅获取字母表。

    >>> [''.join(re.findall('[a-zA-Z]', t)) for t in text]
    ['aQx', 'aub']
    

    【讨论】:

      【解决方案3】:

      您也可以在没有正则表达式的情况下执行此操作:

      from string import ascii_letters
      
      text=['aQx12', 'aub 6 5']
      
      
      >>> [''.join([c for c in sl if c in ascii_letters]) for sl in text]
      ['aQx', 'aub']
      

      【讨论】:

        【解决方案4】:

        您可以删除列表解析中除字母以外的任何字符。

        没有正则表达式解决方案:

        print( [''.join(filter(str.isalpha, s)) for s in ['aQx12', 'aub 6 5']] )
        

        请参阅Python demo。这是一个基于正则表达式的演示:

        import re 
        text=['aQx12', 'aub 6 5']
        newlist = [re.sub(r'[^a-zA-Z]+', '', x) for x in text]
        print(newlist)
        # => ['aQx', 'aub']
        

        Python demo

        如果您需要处理任何 Unicode 字母,请使用

        re.sub(r'[\W\d_]+', '', x)
        

        请参阅regex demo

        【讨论】:

          猜你喜欢
          • 2020-04-18
          • 2014-06-24
          • 2014-05-10
          • 1970-01-01
          • 2011-06-26
          • 2023-01-07
          • 1970-01-01
          • 1970-01-01
          • 2020-06-10
          相关资源
          最近更新 更多