正则表达式满足两个字符串条件

2024-10-04 01:33:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有不同长度/约定的主机名:

tor1er1
tor1x1ms1

对于“tor1er1”,我们可以将其分解为:

'tor' = region
'1' = environment
'er' = type
'1' = number for the device

对于“tor1x1ms1”,我们可以将其分解为:

'tor' = region
'1' = environment
'x1' = cross connect
'er' = type
'1' = number for the device

如您所见,对于tor1x1ms1,交叉连接有一个额外的“x1”。我正在尝试使用正则表达式来容纳这两种类型的字符串。我试过:

import re
hostname = 'tor1er1'
m = re.match(r"([a-zA-Z]+)([0-9]+)([a-zA-Z]+)([0-9]+)([a-zA-Z]+)([0-9]+)",hostname)

因为长度与预期的表达式不匹配。我希望能够访问每个组以获取信息。例如:

region = m.groups(1)
environment = m.groups(2)

Tags: therenumberforenvironmentdevicetyperegion
2条回答

您可能会发现为此使用命名捕获组很方便。您可以使用以下正则表达式来实现这一点

r'^(?P<reg>[a-z]{3})(?P<env>\d)(?:(?P<xcon>[a-z]\d))?(?P<type>[a-z]{2})(?P<nbr>\d)'

对于问题中给出的两个示例字符串,正则表达式提供了以下结果

Full match   : "tor1er1"
Group `reg`  : "tor"
Group `env`  : "1"
Group `type` : "er"
Group `nbr`  : "1"

Full match   : "tor1x1ms1"
Group `reg`  : "tor"
Group `env`  : "1"
Group `xcon` : "x1"
Group `type` : "ms"
Group `nbr`  : "1"

Start your engine!

Python的正则表达式引擎执行以下操作

^                   : match beginning of string
(?P<reg>[a-z]{3})   : match 3 lc letters and save to
                      capture group 'reg'
(?P<env>\d)         : match 1 digit and save to capture
                      group 'env'
(?P<xcon>[a-z]\d)?  : match 1 lc, letter 1 digit, save to
                      capture group 'xcon', make optional
(?P<type>[a-z]{2})  : match 2 lc letters, save to
                      capture group 'type'
(?P<nbr>\d)         : match 1 digit, save to
                      capture group 'nbr'

由于x和1都在其自己的捕获组中,因此您可以将它们同时设置为可选的,这样您就可以继续对相同的数据使用组号

可以考虑锚或字边界^ {CD1>},以防止匹配是较长单词的一部分。

([a-zA-Z]+)([0-9]+)(?:([a-zA-Z]+)([0-9]+))?([a-zA-Z]+)([0-9]+)

Regex demo

相关问题 更多 >