python正则表达式行匹配

2024-05-29 09:46:12 发布

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

我对python还很陌生,需要一些帮助。你知道吗

我有个文件叫pdu.tmp公司包含以下行:

文件夹名称;PDU-8000;位置:;172.27.0.69 文件夹名称;PDU-A8009;位置:;172.27.0.64 文件夹名称;PDU-A8091;位置:;172.27.0.48 ... 你知道吗

我想匹配行包含PDU-并打印到屏幕上

我的问题是我的正则表达式似乎不匹配(我总是一个都没有),即使我使用简单的正则表达式* 我试着剥去我的“线”,因为当我打印“线”的时候,好像有一条新的线。但这也没能解决问题

这是我的密码:

开始

import re

p = re.compile(r"""
Foldername.*            
,NULL
""", re.VERBOSE)

i = 0

output = open('pdu.temp', 'r')

for line in output:
    newline = line.strip() # stripped the line here
    print newline
    m = p.match(newline)
    print m
    if m:
        print "Until now I found " + str(i) + "matches" + '\n'
    #   print i + ":" + line
        i += 1

output.close()

结束

下面是运行脚本后的输出:

Foldername;Contact Name;location: Location;IP Address
None
Foldername;PDU-A8094;location: ;172.27.0.44
None
Foldername;PDU-A8011;location: ;172.27.0.56
None
Foldername;PDU-8000;location: ;172.27.0.69
None
Foldername;PDU-A8009;location: ;172.27.0.64
None
Foldername;PDU-A8091;location: ;172.27.0.48

帮助我了解如何调试这将是伟大的!你知道吗


Tags: re文件夹名称noneoutputlinenewlinelocation
2条回答
  1. 您的正则表达式不匹配,因为文本中没有出现NULL。你知道吗
  2. 在你的代码里我没有被初始化。你知道吗

相反,您应该尝试:

from __future__ import print_statement

import re

p = re.compile(r"""
^
Foldername;PDU
""", re.VERBOSE)

output = open('pdu.temp', 'r')

i = 0;
for line in output:
    newline = line.strip() # stripped the line here
    m = p.match(newline)
    if m:
        print("Until now I found " + str(i) + " matches")
        i += 1
        print('{0}:{1}\n'.format(i, line))

Demo here。你知道吗

请注意,包含了from __future__ import print_statement,因此相同的代码可以在python2.7和python3.x中使用

我不知道你想得到什么,试着发布示例输出。你知道吗

但也许这会符合你的要求?你知道吗

import re
p = re.compile(r'Foldername;(.*);location: (.*);(.*)')
i = 0
with open('input.txt', 'r') as input:
    for line in input:
        m = p.match(line)
        if m:
            print "Until now I found " + str(i) + " matches" + '\n'
        #   print i + ":" + line
            i += 1

如果这是你想要的,考虑改变

if m:
    print "Until now I found " + str(i) + " matches" + '\n'
    i += 1

if m:
    i += 1
    print "Until now I found " + str(i) + " matches" + '\n'

以避免输出为0。 我的输入.txt文件包含:

Foldername;Contact Name;location: Location;IP Address
None
Foldername;PDU-A8094;location: ;172.27.0.44
None
Foldername;PDU-A8011;location: ;172.27.0.56
None
Foldername;PDU-8000;location: ;172.27.0.69
None
Foldername;PDU-A8009;location: ;172.27.0.64
None
Foldername;PDU-A8091;location: ;172.27.0.48

相关问题 更多 >

    热门问题