Roshan Book

My Tech Notebook

Tag Archives: regular expression in python

Python tutorial 9.2–Using Regular Expressions

It is for matching patterns in text

It is implemented in python with “re” module

working

import re

patter=re.compiler(r’ddd’)

if re.search(regex, line): print (line)

example. If you have a text file name raven.txt and wants to print words which matched lenore or nevermore

For pattern and print the line

def main():

fh=open(‘raven.txt’)

for line in fh:

if re.search(‘(len/neverm)ore’, line):

print(line, end=’’)

if __name__=”__main__”:main()

For matching

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search(len/neverm)ore’, line)

if match:

print(match.group())

if __name__=”__main__”:main()

For search and replace

def main():

fh=open(‘raven.txt’)

for line in fh:

print( re.sub(‘(len/neverm)ore’, ‘what replaces with’,line):,ened=’’)

if __name__=”__main__”:main()

For search and replace match method – printing only those line where match and replace happens

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search
(‘(len/neverm)ore’, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

Re Compiling

def main():

fh=open(‘raven.txt’)

pattern=re.compile(‘len/neverm)ore’, re.IGNORECASE)

for line in fh:

match=re.search
(‘attern, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

Python tutorial 9.2–Using Regular Expressions

It is for matching patterns in text

It is implemented in python with “re” module

working

import re

patter=re.compiler(r’ddd’)

if re.search(regex, line): print (line)

example. If you have a text file name raven.txt and wants to print words which matched lenore or nevermore

For pattern and print the line

def main():

fh=open(‘raven.txt’)

for line in fh:

if re.search(‘(len/neverm)ore’, line):

print(line, end=’’)

if __name__=”__main__”:main()

For matching

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search(len/neverm)ore’, line)

if match:

print(match.group())

if __name__=”__main__”:main()

For search and replace

def main():

fh=open(‘raven.txt’)

for line in fh:

print( re.sub(‘(len/neverm)ore’, ‘what replaces with’,line):,ened=’’)

if __name__=”__main__”:main()

For search and replace match method – printing only those line where match and replace happens

def main():

fh=open(‘raven.txt’)

for line in fh:

match=re.search
(‘(len/neverm)ore’, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

Re Compiling

def main():

fh=open(‘raven.txt’)

pattern=re.compile(‘len/neverm)ore’, re.IGNORECASE)

for line in fh:

match=re.search
(‘attern, ‘line)

if match:

print(line.replace(match.group()),’###’

),end=’’)

if __name__=”__main__”:main()

%d bloggers like this: