Roshan Book

My Tech Notebook

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()

Advertisements

5 responses to “Python tutorial 9.2–Using Regular Expressions

  1. Nick Zarczynski October 13, 2011 at 2:34 pm

    WordPress has a built-in plugin for posting source code and syntax highlighting.

    Example:

    def hello():
      print "Hello world!"
    
    hello()
    #==> Hello world!
    

    It will preserve indentation, which is vital for Python code.

  2. Charlie Boria October 20, 2011 at 12:55 am

    Incredible! This blog looks exactly like my old one! It’s on a completely different subject but it has pretty much the same page layout and design. Superb choice of colors!

  3. kahlua cocktail October 20, 2011 at 1:35 pm

    There are some interesting points in time in this article but I don’t know if I see all of them heart to eye . There is some validity but I will take hold judgement until I look into it further. Good clause, thanks and we want more! Added to FeedBurner besides.

  4. atlanta SEO marketing November 12, 2011 at 11:47 pm

    Nice article. Keep up the good work.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: