Saturday 7 June 2014

python regex example1

Task: read a file and print match:


#!/usr/bin/env python

import re

amFile = open('file_name', 'r')
amRe = re.compile('\d{1,5}\s\w+\s\w+\.')   # -> your regex

for line in amFile:
    amOut = re.findall(amRe,line)
    if amOut > 0:
      print (amOut)
amFile.close()



NOTE:
\d{1,5} : any digit from 1 digit to 5 digits  => [0 to 99999 ]
\s : a single space
\w+ : any word at least 1 char or more.
\s : a single space again
\w+ : any word at least 1 char or more.
\. : end with a .

123 Main St.   <= This will match in the above example.



##############################################
 -P, --perl-regexp
              Interpret  PATTERN  as  a  Perl  regular  expression  (PCRE, see
              below).  This is highly experimental and grep  -P  may  warn  of
              unimplemented features.

 grep -P '\d{1,5}' filename



ifconfig | grep -o -P '(\d+\.){3}\d+'
192.168.0.110
192.168.0.255
255.255.255.0
127.0.0.1
255.0.0.0


=============================================


##############################################

No comments:

Post a Comment