获取第二组引号之间的内容

2024-09-29 23:20:45 发布

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

我刚开始使用python,并尝试在引号之间打印内容

我的文件中的文本:

set address "Trust" "45.200.0.0/16" 45.200.0.0 255.255.0.0
set address "Trust" "45.200.1.80/32" 45.200.1.80 255.255.255.255
set address "Trust" "ad.corp" 45.200.1.98 255.255.255.255 "active directory server"
set address "Trust" "Infrasun" 45.200.1.2 255.255.255.255 "DNS/DHCP/all that jazz"
set address "Trust" "NAC Team /16 Subnet" 45.200.0.0 255.255.0.0
set address "Untrust" "207.179.9.4/32" 207.179.9.4 255.255.255.255
set address "Untrust" "Laptop Net" 45.128.0.0 255.255.0.0 "Laptop net for use by team"
set address "Untrust" "VoIP Team Subnet" 45.210.0.0 255.255.0.0

我想打印"45.200.0.0/16","45.200.1.80/32","ad.corp","Infrasun"...,所以不是第一组引号,而是第二组引号

这是我的密码:

mon_fichier = open ("conf.cfg","r")
fichier = mon_fichier.read().splitlines()

import re

for ligne in fichier:

    if re.match('set address', ligne):      
        expression = re.compile('(?<=")(?P<value>.*?)(?=")')
        match = expression.search(ligne)
        print match.group('value')

我只打印了:

Trust
Trust
Trust
Trust
Trust
Untrust
Untrust
Untrust

但正如我所说,我需要:"45.200.0.0/16","45.200.1.80/32","ad.corp","Infrasun"...


Tags: readdressmatchteamad引号setcorp
2条回答

不需要正则表达式,只需使用^{}函数:

for ligne in fichier:
    print(ligne.split('"')[3])

您将在双引号"上拆分每条引入线。第四个匹配组是您想要得到的(记住,Python索引是基于0的)

这里不需要正则表达式,因为您的文件已经格式良好:

import csv

with open('somefile.txt', 'r') as f:
   reader = csv.reader(f, delimiter=' ')
   for row in reader:
       print(row[3])

如果您正在学习正则表达式,请尝试以下操作:

>>> import re
>>> exp = r'^set address "\w+" "(.*?)".*?$'
>>> re.findall(exp, i, re.M)
['45.200.0.0/16', '45.200.1.80/32', 'ad.corp', 'Infrasun', 'NAC Team /16 Subnet', '207.179.9.4/32', 'Laptop Net', 'VoIP Team Subnet']

相关问题 更多 >

    热门问题