我有不同长度/约定的主机名:
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)
您可能会发现为此使用命名捕获组很方便。您可以使用以下正则表达式来实现这一点
对于问题中给出的两个示例字符串,正则表达式提供了以下结果
Start your engine!
Python的正则表达式引擎执行以下操作
由于x和1都在其自己的捕获组中,因此您可以将它们同时设置为可选的,这样您就可以继续对相同的数据使用组号
可以考虑锚或字边界^ {CD1>},以防止匹配是较长单词的一部分。
Regex demo
相关问题 更多 >
编程相关推荐