python - 在python中使用正则表达式在字符串列表中查找匹配关键字后的下一个单词

标签 python regex lambda

我有一个字符串列表,我想在每个字符串中的特定关键字之后提取下一个单词。
当我使用 lambda 函数遍历列表时,我得到的是整个字符串,而不仅仅是关键字后面的下一个词:

import re
s = ["The job ABS is scheduled by Bob.", "The job BFG is scheduled by Alice."]
user = filter(lambda i:re.search('(?<=The job )(\w+)',i),s)
print(*user)

output: The job ABS is scheduled by Bob. The job BFG is scheduled by Alice.
但是,当我为单个字符串尝试相同的代码时,它给出了正确的输出:
import re
s = "The job ABS is scheduled by Bob."
user = re.search('(?<=The job )(\w+)',s)
print(user.group())

output: ABS
如何从第一个代码片段中获得像 (ABS, BFG) 这样的输出?

最佳答案

您可以使用

import re
s = ["The job ABS is scheduled by Bob.", "The job BFG is scheduled by Alice."]
rx = re.compile(r'(?<=The job )\w+')
user = tuple(map(lambda x: x.group() or "", map(rx.search, s)))
print(user)
Python demo .
或者,如果可以有任意数量的空格,请使用
rx = re.compile(r'The\s+job\s+(\w+)')
user = tuple(map(lambda x: x.group(1) or "", map(rx.search, s)))
输出:
('ABS', 'BFG')
在这里,map(rx.search, s)返回匹配数据对象的迭代器或 None s 和外 map(lambda x: x.group(...) or "", ...)获取组的值(与 .group() 的整个匹配或与 .group(1) 的组 1 值),如果没有匹配,则返回空字符串。

关于python - 在python中使用正则表达式在字符串列表中查找匹配关键字后的下一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65725286/

相关文章:

php - preg_match 获取包含 123 和 .txt 之间任何字符的文件?

javascript - JS 中只删除字符串中的一些逗号

php - 获取 html 输入元素的值作为 php 字符串

c++ - 在 C++ 中返回 lambda 函数

java - 方法引用导致原始类型编译器警告,但 lambda 不会

python - 带有python正则表达式的文字括号

Python构造一个字典数据类型?

python - 如何从本身从标准输入读取的标准输入运行 Python 源代码?

python - tkinter 顶级小部件有哪些协议(protocol)

c# - lambda 表达式在内部是如何工作的?