Download Regular Expressions in Python: A Comprehensive Guide - Prof. Katrin E. Erk and more Study notes Linguistics in PDF only on Docsity!
Regular expressions in Python
LIN 350
Words in a Haystack
Katrin Erk
A Python module
for regular expressions
import re
Several functions in re:
re.search(REGEX, STRING): does STRING match the regular expression REGEX? re.findall(REGEX, STRING): what are all the matches of REGEX in STRING? re.sub(REGEX, REPLACEMENT, STRING): replace all occurrences of REGEX in STRING by REPLACEMENT (in the simplest case, a string)
Regular expressions in Python:
Familiar constructs
^Y Y at the beginning of the string
Z$ Z at the end of the string
. any character (but not newline)
x|y either x or y
Using regular expressions in Python
>>> import re
>>> re.search("[aeiou]", "hello")
<_sre.SRE_Match object at 0x3a4cd0>
>>> re.search("[aeiou]", "why")
>>> result = re.search("[aeiou]", "hello")
>>> result.group()
'e'
>>> result.span()
re.search() finds the first match (and first match only). It returns a SRE_Match object, or None if no match was found. If ‘result’ is a SRE_Match object, result.group() returns the matching string, result.span() returns start and end index of the match, result.start() returns the start index of the match, result.end() returns the end index of the match.
Regular expressions in Python:
New constructs
In grep: bracket expressions like [:digit:] In Python and egrep: backslash + letter
\d digit, equivalent to [0-9]
\D non-digit: [^0-9]
\s whitespace, equivalent to [ \t\n\r\f\v]
\S non-whitespace
\w alphanumeric character,
equivalent to [a-zA-Z0-9_]
\W non-alphanumeric character
Using predefined character sets
>>> import re
>>> m = re.search(“\w+\s=\s\w+”,
“ key = value “)
>>> m.group()
'key = value'
>>> m = re.search("^\s*\d+(th|st|nd|rd)\s+\w+",
"1st of November")
>>> m.group()
'1st of'
Changing the behavior of re:
Flags
re.VERBOSE:
whitespace in the regular expression ignored,
except in bracket expressions or as \s
comments at end of lines, starting with
longer regular expression strings
using “””…..”””
Highly recommended!
This lets you write regular expressions that are
actually readable
Changing the behavior of re:
Flags
re.IGNORECASE:
Ignore case. [A-Z] is the same as [a-z]
re.LOCALE:
Make definition of whitespace (\s), of what an alphanumeric character is (\w) dependent on locale
re.MULTILINE:
Use this on multiline strings, i.e. strings that contain newline. ^ matches beginning of string and beginning of each line $ matches end of string and end of each line
re.DOTALL: make “.” also match newline
Regular expressions in Python:
More anchors
Problem with using \b: in a string, it usually means
“backspace”
Workaround: tell Python to treat the regular
expression as a “raw” string
>>> import re
>>> re.search(“\ba”, “a”)
>>> re.search(r”\ba”, “a”)
<_sre.SRE_Match object at 0x3606e8>
>>> re.search(r"[aeiou]\w+", "pick one").group()
'ick'
>>> re.search(r"\b[aeiou]\w+", "pick one").group()
'one'
Compiling regular expressions
Up to now:
re.search(“[aeiou]”, “this is a string”) re.findall(“[aeiou]”, “this is a string”)
Other option: make a regular expression object
import re myreg = re.compile(“[aeiou]”) myreg.search(“this is a string”).group() ‘i’ myreg.findall(“this is a string”) ['i', 'i', 'a', 'i']
Taking strings apart: brackets
>>> m = re.search("(\w+)\s=\s(\w+)",
" key = value")
>>> m.groups()
('key', 'value')
Putting brackets () around parts of a regular
expression: these parts are retrieved separately
Retrieving these parts:
Method of Match objects groups()
Taking strings apart: brackets
>>> re.findall("(\w+)\s=\s(\w+)",
" key = value")
[('key', 'value')]
Brackets used with re.findall():
For each match, the bracketed parts are returned in a
tuple
re.findall("(\w+)\s=\s(\w+)", """ key = value anotherkey = anothervalue key3 = val """, re.MULTILINE) [('key', 'value'), ('anotherkey', 'anothervalue'), ('key3', 'val3')]
Tasks
Find and extract from a single line of text: Ordinal numbers, for example: 1st, 2nd, 3rd, 12th, 13,089th words with 7-12 letters In text that may consist of multiple lines, match and extract single lines In an XML tag, extract all attribute-value pairs. Assume that your string consists of just one opening XML tag. Examples: <s id=“ 123 ” root=“123_5”> (Both “” and ‘’ are possible around values!)