Python正则表达式过滤匹配模式的字符串列表

lok*_*art 5 python regex list subset

我更多地使用 R,而且我在 R 中更容易做到:

> test <- c('bbb', 'ccc', 'axx', 'xzz', 'xaa')
> test[grepl("^x",test)]
[1] "xzz" "xaa"
Run Code Online (Sandbox Code Playgroud)

但是如果test是一个列表,如何在python中做到这一点?

PS我正在使用谷歌的python练习学习python。我更喜欢使用回归表达式。

Abh*_*jit 7

您可以使用以下命令查找列表中是否有任何字符串开头'x'

>>> [e for e in test if e.startswith('x')]
['xzz', 'xaa']
>>> any(e.startswith('x') for e in test)
True
Run Code Online (Sandbox Code Playgroud)

  • @lokheart 你绝对可以在上面的列表理解中使用 `re.match` 代替 `starswith` 。 (2认同)

Wik*_*żew 5

一般来说,你可以使用

import re                                  # Add the re import declaration to use regex
test = ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] # Define a test list
reg = re.compile(r'^x')                    # Compile the regex
test = list(filter(reg.search, test))      # Create iterator using filter, cast to list 
# => ['xzz', 'xaa']
Run Code Online (Sandbox Code Playgroud)

请参阅Python 演示

使用说明

  • re.search在字符串中的任何位置找到第一个正则表达式匹配并返回一个匹配对象,否则None
  • re.match仅在字符串 start 处查找匹配项,它不需要完整的字符串匹配项。所以,re.search(r'^x', text)=re.match(r'x', text)
  • re.fullmatch只有当完整的字符串的模式匹配,返回匹配,所以,re.fullmatch(r'x')= re.match(r'x\Z')= re.search(r'^x\Z')

如果您想知道r''前缀的含义,请参阅Python - 在使用正则表达式查找句点(句号或 .)时,我应该使用字符串前缀 r 吗?Python 正则表达式 -r 前缀