【问题标题】:Regular Expression in Middle of a String in a List (Python)列表中字符串中间的正则表达式(Python)
【发布时间】:2018-12-26 03:26:39
【问题描述】:

我正在尝试使用正则表达式来匹配字符串中间的模式,其中字符串也在列表中。我可以找到一个问题或另一个问题的解决方案,但对如何将两者结合起来感到困惑。

首先,我使用this solution 作为模板。我在“cat”和“cow”之后添加了文本,所以它们现在是“cat named bob”和“cow also named bob”。目标是从列表中的这两个字符串中提取单词“named”,并将它们作为列表中的项目返回(例如 ['named', 'named'])。

mylist = ["dog", "cat named bob", "wildcat", "thundercat", "cow also named bob", "hooo"]
r = re.compile('named')
newlist = list(filter(r.search, mylist)) 
print(newlist)

但是,如果我使用 r.search 或 r.findall,我会得到整个字符串,而不仅仅是中间部分。如果我使用 r.match,我不会得到任何结果。我在searching in the middle of a string 上发现了一些 Stack Overflow 查询,但它们似乎不适用于在字符串中查找匹配项的解决方案。我尝试了以下代码,但没有成功:

newlist = list(filter(r.match.group(1), mylist)) 

如何结合这两个任务并在列表内的字符串中间提取文本?

【问题讨论】:

标签: python regex string list


【解决方案1】:

使用filter(r.search, mylist),您只会收到项目内任何地方存在正则表达式匹配的所有项目。当您使用filter(r.match, mylist) 时,您只会获得匹配位于字符串开头的项目。

你可以使用

import re
mylist = ["dog", "cat named bob", "wildcat", "thundercat", "cow also named bob", "hooo"]
r = re.compile('named')
# You might gfo through the list, check if there is match 
# by running a re.search, and there is, extract it
newlist = [r.search(x).group() for x in mylist if r.search(x)]
print(newlist)
# Or, use map to get the matches first, and then 
# check if the object is not None and then retrieve the value
newlist = [x.group() for x in map(r.search, mylist) if x]
print(newlist)

Python demo

【讨论】:

  • 此解决方案对mylist 中的每个匹配项应用相同的搜索两次,这似乎很浪费。
  • @blhsing 是的,[x.group() for x in map(r.search, mylist) if x] 只会执行一次。我想用map 更新解决方案,但我看到你已经发布了。
【解决方案2】:

使用列表理解:

print([m.group() for m in map(r.search, mylist) if m])

这个输出:

['named', 'named']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 2016-01-10
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多