正则表达式不在python中工作,但在在线正则表达式工具中工作

2024-09-28 05:27:33 发布

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

我试图从configs中获取一个主机名,有时会在config中的主机名中添加一个-p或-s,这实际上不是主机名的一部分。 因此,我编写了这个正则表达式来从配置文件中获取主机名:

REGEX_HOSTNAME = re.compile('^hostname\s(?P<hostname>(\w|\W)+?)(-p|-P|-s|-S)?$\n',re.MULTILINE)

hostname = REGEX_HOSTNAME.search(config).group('hostname').lower().strip()

这是我在其上使用正则表达式的配置的示例部分:

terminal width 120
hostname IGN-HSHST-HSH-01-P
domain-name sample.com

但是在我的主机名结果列表的末尾仍然是-p

ign-hshst-hsh-01-p
ign-hshst-hsh-02-p
ign-hshst-hsd-10
ign-hshst-hsh-01-S
ign-hshst-hsd-11
ign-hshst-hsh-02-s

在Regex101在线测试仪中,它可以工作,-p是最后一组的一部分。在我的python(2.7)脚本中,它不起作用

奇怪的行为是,当我使用稍微修改过的2遍正则表达式时,它可以工作:

REGEX_HOSTNAME = re.compile(r'^hostname\s*(?P<hostname>.*?)\n?$', re.MULTILINE)
REGEXP_CLUSTERNAME = re.compile('(?P<clustername>.*?)(?:-[ps])?$')
            hostname = REGEX_HOSTNAME.search(config).group('hostname').lower().strip()
            clustername = REGEXP_CLUSTERNAME.match(hostname).group('clustername')

现在Hostname有了全名,clustername在末尾没有可选的'-p'


Tags: reconfigsearchgrouplowerhostnameregex主机名
1条回答
网友
1楼 · 发布于 2024-09-28 05:27:33

你可以用

import re

config=r"""terminal width 120
hostname IGN-HSHST-HSH-01-P
domain-name sample.com"""

REGEX_HOSTNAME = re.compile(r'^hostname\s*(.*?)(?:-[ps])?$', re.MULTILINE|re.I)
hostnames =[ h.lower().strip() for h in REGEX_HOSTNAME.findall(config) ]
print(hostnames) # => ['ign-hshst-hsh-01']

Python demo^hostname\s*(.*?)(?:-[ps])?$正则表达式匹配:

  • ^-行的开始(由于re.MULTILINE,它也与换行后的位置匹配)
  • hostname-一个单词(不区分大小写,因为re.I
  • \s*-0+空格
  • (.*?)-第1组:除换行符以外的零个或多个字符,尽可能少
  • (?:-[ps])?-可选出现-ps(不区分大小写!)
  • $-行的结尾(由于re.MULTILINE

regex demo online

相关问题 更多 >

    热门问题