使用Python的正则表达式.match()方法获取下划线之前和之后的字符串

时间:2016-08-25 19:30:37

标签: python regex string iterator

我有以下代码:

tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]

for table in tablesInDataset:
    tableregex = re.compile("\d{8}")
    tablespec = re.match(tableregex, table)

    everythingbeforedigits = tablespec.group(0)
    digits = tablespec.group(1)

我的正则表达式只应返回字符串,如果它包含下划线后的8位数字。返回字符串后,我想使用.match()使用.group()方法获取两个组。第一组应包含一个字符串,将包含数字前的所有字符,第二组应包含一个包含8位数字符的字符串。

使用.match().group()获取我想要的结果的正确正则表达是什么?

4 个答案:

答案 0 :(得分:5)

使用捕获组:

>>> import re
>>> pat = re.compile(r'(?P<name>.*)_(?P<number>\d{8})')
>>> pat.findall(s)
[('henry_jones', '12345678')]

如果您需要,您可以获得命名组的优秀功能:

>>> match = pat.match(s)
>>> match.groupdict()
{'name': 'henry_jones', 'number': '12345678'}

答案 1 :(得分:4)

tableregex = re.compile("(.*)_(\d{8})")

答案 2 :(得分:2)

我认为此模式应符合您的要求:(.*?_)(\d{8})

第一组包括最多8位数的所有内容,包括下划线。第二组是8位数。

如果您不想包含下划线,请改用:(.*?)_(\d{8})

答案 3 :(得分:1)

你走了:

import re

tablesInDataset = ["henry_jones_12345678", "henry_jones", "henry_jones_123"]
rx = re.compile(r'^(\D+)_(\d{8})$')

matches = [(match.groups()) \
            for item in tablesInDataset \
            for match in [rx.search(item)] \
            if match]
print(matches)

比任何 dot-star-soup 更好:)

相关问题