|
Regular expressions made easy - building from components
There seems to be a certain macho desire in many programmer's minds to write a single complicated regular expression to match against an input line, ignorning the structured approach that everyone accepts quite cheerfully in almost every other case. Have a look at this Python line:
wholeline = r"\d\d-...-\d\d\d\d\s+(\d\d):(\d\d):(\d\d.\d\d),\s+(-?\d+\.\d+),\s+(-?\d+\.\d+),(-?\d+\.\d+),\s+(-?\d+\.\d+),(-?\d+\.\d+),\s+(-?\d+\.\d+)"
Impressive, isn't it?
Yes
Easy to follow, isn't it?
No!
Much better to build it up from a series of components:
date = r"\d\d-...-\d\d\d\d"
time = r"(\d\d):(\d\d):(\d\d.\d\d)"
whitespace = r"\s+"
floater = r"(-?\d+\.\d+)"
wholeline = date + whitespace + time + "," + whitespace + \
floater + "," + whitespace + floater + "," + floater + \
"," + whitespace + floater + "," + floater + "," + \
whitespace + floater
These examples are from the Python Course I have just concluded - the full example is here - where a log file was to be analysed and a short report generated to highlight any changes in readings of over 1% from one line of the data to the next in any of the data columns.
(written 2007-08-16 20:25:39)
Associated topics are indexed under Y115 - Additional Python FacilitiesQ806 - Regular Expression CookbookR109 - Ruby - Strings and Regular ExpressionsT247 - Tcl/Tk - Advanced Regular ExpressionsP212 - Perl - More on Character Strings
Some other Articles
Dates for Easter - 2008 to 2015Good to be homeTroy, up state New YorkPython class rattling aroundRegular expressions made easy - building from componentsLast elements in a Perl or Python listHeading Upstate New YorkRuby, Ruby, Ruby. Rails, Rails, Rails.Plastic or ChinaIn the USA for a few days
|
1891 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|