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

问题描述 投票:4回答:4

我有以下代码:

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()获取我正在寻找的结果的正确正则表达式是什么?

python regex string iterator
4个回答
4
投票
tableregex = re.compile("(.*)_(\d{8})")

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'}

2
投票

我认为这种模式应该符合你的需要:(.*?_)(\d{8})

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

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


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)

比任何点星汤更好:)

© www.soinside.com 2019 - 2024. All rights reserved.