import re re for regular expression of course import fileinput monthNumber

Import re re for regular expression of course import

This preview shows page 20 - 22 out of 22 pages.

The Script — which replaces '25 Sep 1986' by '09-25-1986', etc. import re # "re" for "regular expression," of course import fileinput monthNumber = {} # Create an empty dictionary monthNumber["Jan"] = "01" # Create dictionary entries monthNumber["Feb"] = "02" monthNumber["Mar"] = "03" monthNumber["Apr"] = "04" monthNumber["May"] = "05" monthNumber["Jun"] = "06" monthNumber["Jul"] = "07" monthNumber["Aug"] = "08" monthNumber["Sep"] = "09" monthNumber["Oct"] = "10" monthNumber["Nov"] = "11" monthNumber["Dec"] = "12" compiledPattern = re.compile( r'(^.*) (\d\d) ([A-Za-z]{3,3}) (\d\d\d\d) (.*)$' ) for nextLineOfInput in fileinput.input(): matchedObject = re.match( compiledPattern, nextLineOfInput ) ( prefix, dayString , monthString , yearString , suffix ) = matchedObject.group( 1, 2 , 3 , 4 , 5 ) print prefix + monthNumber[ monthString ] + "-" + dayString + "-" + yearString + suffix Which produces: 'ALG','1','15.00','Written problem',' 09 - 25 - 1986 ' 'ALG','2','15.00','Written problem',' 10 - 19 - 1986 ' 20
Image of page 20
CS200 Winter 2018 Regular Expressions To build a complex pattern start simple add to pattern one small piece at a time test as you go When doing replacements build and test the search pattern first then build the replacement Save useful patterns in a text file If something doesn’t seem to work, check the documentation details of regular expressions syntax vary from application to application eg MS Word uses non-standard syntax, and lacks some standard features (sigh...) 21 Hints For Using Regular Expressions
Image of page 21
CS200 Winter 2018 Regular Expressions Useful Software for Experimenting With Regular Expressions RegExplorer (Shareware for Mac & Windows, $12 US) A Better Finder Rename (Shareware for Mac & Windows, $20 US) Mac: Windows: A Better Finder Select ($10) is interesting, too. 22
Image of page 22

You've reached the end of your free preview.

Want to read all 22 pages?

  • Spring '17
  • Text editor, Regular expression, regular expressions, Pattern matching

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture