正则表达式结果与测试仪不匹配

时间:2019-02-17 21:21:13

标签: python regex python-2.7

我是Python的新手...

过了几天,如果谷歌搜索,我仍然无法正常工作。

我的脚本:

import re
pattern = '^Hostname=([a-zA-Z0-9.]+)'
hand = open('python_test_data.conf')
for line in hand:
    line = line.rstrip()
    if re.search(pattern, line) :
        print line

测试文件内容:

### Option: Hostname
#       Unique, case sensitive Proxy name. Make sure the Proxy name is known to the server!
#       Value is acquired from HostnameItem if undefined.
#
# Mandatory: no
# Default:
# Hostname=

Hostname=bbg-zbx-proxy

脚本结果:

ubuntu-workstation:~$ python python_test.py
Hostname=bbg-zbx-proxy

但是当我在测试仪中测试了正则表达式时,结果是:https://regex101.com/r/wYUc4v/1

我需要一些建议,但我不能只获得bbg-zbx-proxy作为脚本输出。

2 个答案:

答案 0 :(得分:4)

您已经写了一个正则表达式来捕获比赛的一部分,因此您也可以使用它。另外,将您的角色类更改为包括-并摆脱line.strip()调用,这对于您的表达式不是必需的。
总共可以归结为:

import re
pattern = '^Hostname=([-a-zA-Z0-9.]+)'
hand = open('python_test_data.conf')
for line in hand:
    m = re.search(pattern, line)
    if m:
        print(m.group(1))
        #       ^^^

答案 1 :(得分:1)

简单的解决方案是在等号上进行拆分。您知道它将始终包含该内容,并且您将能够忽略拆分中的第一项。

import re

pattern = '^Hostname=([a-zA-Z0-9.]+)'
hand = open('testdata.txt')
for line in hand:
    line = line.rstrip()
    if re.search(pattern, line) :
        print(line.split("=")[1])   # UPDATED HERE
相关问题