简体   繁体   English

Python模式与正则表达式,findall和组匹配

[英]Python pattern matching with regex, findall and groups

I had a script that scanned in piece of text and returned me a group which I would save to an array. 我有一个脚本在一段文字中扫描并返回给我一个组,我将保存到一个数组。 The code looks like this: 代码如下所示:

pattern = re.compile(r'<span id="first_name">(.+?)</span>')
matches = pattern.findall(str(my_text_file))

This works awesome and I could scan first names in my text file and write them into an array doing this: 这很棒,我可以在我的文本文件中扫描名字并将它们写入一个数组中:

for firstname in matches:
    if firstname not in list_of_names:
        list_of_names.append(firstname)

But now I need to expand my pattern to retrieve two groups instead of one, and I have no idea how I am supposed to get to the second group. 但是现在我需要扩展我的模式以检索两个组而不是一个,我不知道我应该如何进入第二组。

When I have something like: 当我有类似的东西:

pattern = re.compile(r'<span id="first_name">(.+?)</span><span id="last_name">(.+?)</span>')
matches = pattern.findall(str(my_text_file))

How am I supposed to put those second group (last names) in a different array? 我该如何将第二组(姓氏)放在不同的数组中?

for match in matches:
    first_names.append(match[0])
    last_names.append(match[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM