Python regex examples

Write text from file temp1.txt to named.txt (use the ‘a’ option if you want to append instead)

 
#!/usr/bin/python
import os
import re
with open("named.txt", "wt") as fout:
    with open("templ.txt", "rt") as fin:
        for line in fin:
            fout.write(line)

Search for a string in a file and display the Result

 
import re
text="XXX"
file ='templ.txt'
for line in open(file):
    if text in line:
        print line

Search for a string by using compile in a file and display the Result

 
import re
text = "XXX"
pattern = re.compile(text)
file = 'templ.txt'
of = open(file)
for line in of.readlines():
    if re.search(pattern,  line):
        print line

Append the contents of a file to another file

import re
import os
fo = open("templ.txt","r")
fi = open("named.txt","a")
for line in fo:
    fi.write(line)
    #print line
fi.close()
fo.close()

Isolating text field from a variable

text = '11:47:55.045 -T- MFS_TEST10 Received FIX Message 3  8=FIX.4.2|9=146|35=D|34=3|49=MFS_TEST10|52=20120726-15:47:55|56=CCG|115=YYYC|11=AAA 0981/07262012|54=1|38=100000|55=ACL|40=1|47=A|60=20120726-15:47:55|21=1|207=N|10=044|'
print re.split(r'\s', text)[2]
Output
MFS_TEST10

Isolating text fields from a file.

 import re
#!/usr/bin/python
import re
import os
import fnmatch
fo = open("templ.txt", "r")
for line in fo:
        print line
        print re.split(r'\s', line, re.I|re.M)[1]
Provided the text with in the file was "Road 123 Str NY USA 11214"
Output 123

Searching for specific type files.

 

filenames = ['httpd.conf', 'samba.conf', 'header.h', 'socket.net']

[loop for loop in filenames if loop.endswith(('.h'))]
for loop in filenames:
    if loop.endswith('.h') or loop.startswith('httpd'):
        print loop
Output
httpd.conf
header.h

Searching through a List

 
#Great use with os.dirlist
addresses = [
    '5412 N CLARK ST',
    '1060 W ADDISON ST',
    '1039 W GRANVILLE AVE',
    '2122 N CLARK ST',
    '4802 N BROADWAY',
]

for loop in addresses:
    if fnmatch.fnmatchcase(loop, '* ST'):
        print loop
Output
5412 N CLARK ST
1060 W ADDISON ST
 2122 N CLARK ST

Print specific fields from a string

 
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
pattern = re.compile('Today\s\w+\s\d+\W\d+\W\d+', re.IGNORECASE)
searpatt = re.search(pattern, text)
print (searpatt.group())

Output

Today is 11/27/2012

Replace specific fields of text

print text
#!/usr/bin/python
import re

text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
newt = "Yesterday"
pattern = re.compile('Today\s\w+\s\d+\W\d+\W\d+', re.IGNORECASE)
searpatt = re.search(pattern, text)
print re.sub(pattern, newt, text)

Output

Yesterday. PyCon starts 3/13/2013.

Print a specific element of the split you created

#!/usr/bin/python
import re

text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
newt = "Yesterday"
pattern = re.compile('Today\s\w+\s\d+\W\d+\W\d+', re.IGNORECASE)
searpatt = re.search(pattern, text)
print text
print re.split(pattern, text )[1]

PyCon starts 3/13/2013.

Replace strings in a file

#!/usr/bin/python
import os
import re
text_ip = "#listen_addresses = 'localhost'"
        subtext_ip = "listen_addresses = '10.0.0.27'"
        text_port = "#port = 5432"
        subtext_port = "port = 5432"

        s = open("/home/postgres/postgres94/postgresql.conf").read()
        s = s.replace(text_ip, subtext_ip)
        s = s.replace(text_port, subtext_port)
        f = open("/home/postgres/postgres94/postgresql.conf", 'w')
        f.write(s)
        f.close()
Share Button

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.