Python捕获特定单词后的特定数字
我试图从这句话中捕捉“图书id:”(与isbn类似,只是它有数字)。我查看了堆栈上的ISBN编号示例,并尝试了不同类型的正则表达式组合,但始终无法将它们捕获到单个列表中。我错过了什么Python捕获特定单词后的特定数字,python,python-3.x,Python,Python 3.x,我试图从这句话中捕捉“图书id:”(与isbn类似,只是它有数字)。我查看了堆栈上的ISBN编号示例,并尝试了不同类型的正则表达式组合,但始终无法将它们捕获到单个列表中。我错过了什么 sentence="List of book ids that are important to read book id: A83827-121-1-23-1341-2315ad3 book id: N32-12-1-23-1341-2342 and book id: A334121A313412342"
sentence="List of book ids that are important to read book id: A83827-121-1-23-1341-2315ad3 book id: N32-12-1-23-1341-2342 and book id: A334121A313412342"
isbn = re.compile("(?:[0-9]{3}-)?[0-9]{1,5}-[0-9]{1,7}-[0-9]{1,6}-[0-9][A-Z]",re.IGNORECASE)
matches = []
for line in sentence:
matches.extend(isbn.findall(line))
print(line)
尝试以如下方式捕获最终输出:
['A83827-121-1-23-1341-2315ad3','N32-12-1-23-1341-2342','A334121A313412342']
请注意,您的
for
循环将迭代每个字符:您不需要它
以下是您可以使用的正则表达式:
isbn = re.compile(r"book id: ([\w-]+)")
print(isbn.findall(sentence))
输出:
['A83827-121-1-23-1341-2315ad3', 'N32-12-1-23-1341-2342', 'A334121A313412342']
说明:
匹配字母数字字符([\w-]+
)和连字符的任何(非空)序列\w
- 括号表示捕获组,
将只返回该组中匹配的内容,因此不包括“book id:”findall