Licence |
Regular Expressions in PythonToday I (finally) had the need to substitute something in a string. My immediate thought, based on my time as a Perl nut, was "use regular expressions!". So I had to get together some resources about how to use regular expressions in Python.
I used 3 resources in putting this together:
Character Escape CodesNaturally, the first place to start. Just wanted to check that they are the same as Perl. Here they are: \ Newline Continuation Regular Expression MetacharactersAgain, nothing surprising here - the same as Perl. . Any character Repetition Specifiers* 0 or more repetitions FlagsDOTALL, S Make . match any character, including newlines Search Functionsmatch() Determine if the RE matches at the beginning of the string. Result Object Functionsgroup() Return the string matched by the RE Simple example>>> import re Note that if you are going to use the search a lot, you can improve
performance by compiling the regex ahead of time using
're.compile(regex)' Other points of interest You can use a regex as the basis for a split or substitution, as follows >>> regex = re.compile(r'\W+') #the regex for word boundaries |