Regular Expression in Python

use   

import re

You can use Regular Expression (module included in Python version 3x, read HOWTO here) to try writing regex.  Here is a simple code that I tried yesterday. The code read the whole file line-by-line and try to split the line into individual word.  Regex is used to capture the word and recognise separators.  By default, split() separates words by space.  We use regex "sep" to recognise 1) any character 2) parentheses 3) minus sign.  Here is the code:
 
# read input file and separate words
#   16 aug 2017

import re

sep = '[\s*()-]'

def process(line):
    # e = line.split()
    # print(e)
    e = [x for x in re.compile(sep).split(line)]
    print(e)
    for w in e:
        if len(w) > 0: print(w)

def readfile(filename):
    infile  = open(filename,'r')
    for line in infile:
        if line[-1] == '\n':     # strip newline
            line = line[:-1]
        print('>',line)
        process(line)
    infile.close()

def main():
    readfile('fac.txt')


Here is the sample input file "fac.txt"

// fac.txt

fac(n)
  if n == 0 return 1
  return n * fac(n-1)

main()
  print(fac(6))


Play around with this piece of code and try to write different Regex  to see how to match the different pattern.

last update 17 Aug 2017