I have a following text file as sample.txt :
xe-4/3/1.1596
xe-4/3/1.1528
ae2.670
xe-4/3/1.1503
ae2
xe-4/3/1.1478
xe-4/3/1.1475
xe-4/3/1.1469
xe-4/3/1
xe-4/3/1.3465
xe-4/0/0.670
xe-4/0/0
xe-4/3/1.1446
xe-4/0/0.544
xe-4/3/1.1437
gr-5/0/0
gr-5/0/0.10
lo0.16384
lo0.16385
em1
em1.0
cbp0
demux0
irb
pip0
pp0
ae0
This is the list of interfaces of a router. I need to print out the lines (interfaces) which contain: xe,ae,gr but the ones which does not containg dot, eg xe-4/3/1 , gr-5/0/0 , ae2 etc.
Trying the following code but it does not work:
import re
file = open('sample.txt','r')
string = file.read()
for f in string:
matchObj = re.findall("(xe|ae|gr)[^.]*$", f)
if matchObj:
print f
Checked my regex (xe|ae|gr)[^.]*$ at http://regexr.com/ and it matches the lines I want. Could you tell me what am I doing wrong.
for f in string:
will iterate over characters in file; you want to iterate over lines. I suggest the following code instead:
# use the with statement to open the file
with open('sample.txt') as file:
for line in file:
# use re.search to see if there is match on the line;
# but we do not care about the actual matching strings
if re.search("(xe|ae|gr)[^.]*$", line):
print line
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.