当在数组中执行正则表达式搜索时,返回为空。

2024-09-29 01:21:30 发布

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

在数组中执行regex搜索时,返回为空

脚本

array = ['GW-date45:ger-date45:mySAPgives','DC-date48ccc:date48:mySAP']

# REGEX
hostname = []
for node in array:
    hostname.append(re.findall(r'^[^-]*\K-([^:]+)', node))

for line in hostname:
    print(line)

输出

[]
[]

REGEX101


Tags: in脚本nodeforline数组dcarray
1条回答
网友
1楼 · 发布于 2024-09-29 01:21:30

Python re不支持^{} construct

似乎您甚至不需要它,因为您只需要捕获组1的值。使用

import re
array = ['GW-date45:ger-date45:mySAPgives','DC-date48ccc:date48:mySAP']
hostname = []
for node in array:
    m = re.search(r'^[^-]*-([^:]+)', node)
    if m:
        hostname.append(m.group(1))

for line in hostname:
    print(line)

参见Python demo。输出:

date45
date48ccc

相关问题 更多 >