This module provides regular expression matching operations similar tothose found in Perl.
Both patterns and strings to be searched can be Unicode strings as well as8-bit strings. However, Unicode strings and 8-bit strings cannot be mixed:that is, you cannot match an Unicode string with a byte pattern orvice-versa; similarly, when asking for a substitution, the replacementstring must be of the same type as both the pattern and the search string.
Regular expressions use the backslash character ('\') to indicatespecial forms or to allow special characters to be used without invokingtheir special meaning. This collides with Python’s usage of the samecharacter for the same purpose in string literals; for example, to matcha literal backslash, one might have to write'\\\\' as the patternstring, because the regular expression must be\\, and eachbackslash must be expressed as\\ inside a regular Python stringliteral.
The solution is to use Python’s raw string notation for regular expressionpatterns; backslashes are not handled in any special way in a string literalprefixed with'r'. Sor"\n" is a two-character string containing'\' and'n', while"\n" is a one-character string containing anewline. Usually patterns will be expressed in Python code using this rawstring notation.
It is important to note that most regular expression operations are available asmodule-level functions and methods oncompiled regular expressions. The functions are shortcutsthat don’t require you to compile a regex object first, but miss somefine-tuning parameters.
See also
A regular expression (or RE) specifies a set of strings that matches it; thefunctions in this module let you check if a particular string matches a givenregular expression (or if a given regular expression matches a particularstring, which comes down to the same thing).
Regular expressions can be concatenated to form new regular expressions; ifAandB are both regular expressions, thenAB is also a regular expression.In general, if a stringp matchesA and another stringq matchesB, thestringpq will match AB. This holds unlessA orB contain low precedenceoperations; boundary conditions betweenA andB; or have numbered groupreferences. Thus, complex expressions can easily be constructed from simplerprimitive expressions like the ones described here. For details of the theoryand implementation of regular expressions, consult the Friedl book referencedabove, or almost any textbook about compiler construction.
A brief explanation of the format of regular expressions follows. For furtherinformation and a gentler presentation, consult theRegular Expression HOWTO.
Regular expressions can contain both special and ordinary characters. Mostordinary characters, like'A','a', or'0', are the simplest regularexpressions; they simply match themselves. You can concatenate ordinarycharacters, solast matches the string'last'. (In the rest of thissection, we’ll write RE’s inthisspecialstyle, usually without quotes, andstrings to be matched'insinglequotes'.)
Some characters, like'|' or'(', are special. Specialcharacters either stand for classes of ordinary characters, or affecthow the regular expressions around them are interpreted. Regularexpression pattern strings may not contain null bytes, but can specifythe null byte using a\number notation such as'\x00'.
The special characters are:
Either escapes special characters (permitting you to match characters like'*','?', and so forth), or signals a special sequence; specialsequences are discussed below.
If you’re not using a raw string to express the pattern, remember that Pythonalso uses the backslash as an escape sequence in string literals; if the escapesequence isn’t recognized by Python’s parser, the backslash and subsequentcharacter are included in the resulting string. However, if Python wouldrecognize the resulting sequence, the backslash should be repeated twice. Thisis complicated and hard to understand, so it’s highly recommended that you useraw strings for all but the simplest expressions.
Used to indicate a set of characters. In a set:
(One or more letters from the set'a','i','L','m','s','u','x'.) The group matches the empty string; theletters set the corresponding flags:re.A (ASCII-only matching),re.I (ignore case),re.L (locale dependent),re.M (multi-line),re.S (dot matches all),andre.X (verbose), for the entire regular expression. (Theflags are described inModule Contents.) Thisis useful if you wish to include the flags as part of the regularexpression, instead of passing aflag argument to there.compile() function.
Note that the(?x) flag changes how the expression is parsed. It should beused first in the expression string, or after one or more whitespace characters.If there are non-whitespace characters before the flag, the results areundefined.
Similar to regular parentheses, but the substring matched by the group isaccessible via the symbolic group namename. Group names must be validPython identifiers, and each group name must be defined only once within aregular expression. A symbolic group is also a numbered group, just as ifthe group were not named.
Named groups can be referenced in three contexts. If the pattern is(?P<quote>['"]).*?(?P=quote) (i.e. matching a string quoted with eithersingle or double quotes):
| Context of reference to group “quote” | Ways to reference it |
|---|---|
| in the same pattern itself |
|
| when processing match objectm |
|
| in a string passed to thereplargument ofre.sub() |
|
Matches if the current position in the string is preceded by a match for...that ends at the current position. This is called apositive lookbehindassertion.(?<=abc)def will find a match inabcdef, since thelookbehind will back up 3 characters and check if the contained pattern matches.The contained pattern must only match strings of some fixed length, meaning thatabc ora|b are allowed, buta* anda{3,4} are not. Note thatpatterns which start with positive lookbehind assertions will not match at thebeginning of the string being searched; you will most likely want to use thesearch() function rather than thematch() function:
>>>importre>>>m=re.search('(?<=abc)def','abcdef')>>>m.group(0)'def'
This example looks for a word following a hyphen:
>>>m=re.search('(?<=-)\w+','spam-egg')>>>m.group(0)'egg'
The special sequences consist of'\' and a character from the list below.If the ordinary character is not on the list, then the resulting RE will matchthe second character. For example,\$ matches the character'$'.
Matches the empty string, but only at the beginning or end of a word.A word is defined as a sequence of Unicode alphanumeric or underscorecharacters, so the end of a word is indicated by whitespace or anon-alphanumeric, non-underscore Unicode character. Note that formally,\b is defined as the boundary between a\w and a\W character(or vice versa), or between\w and the beginning/end of the string.This means thatr'\bfoo\b' matches'foo','foo.','(foo)','barfoobaz' but not'foobar' or'foo3'.
By default Unicode alphanumerics are the ones used, but this can be changedby using theASCII flag. Inside a character range,\brepresents the backspace character, for compatibility with Python’s stringliterals.
Most of the standard escapes supported by Python string literals are alsoaccepted by the regular expression parser:
\a \b \f \n\r \t \u \U\v \x \\
(Note that\b is used to represent word boundaries, and means “backspace”only inside character classes.)
'\u' and'\U' escape sequences are only recognized in Unicodepatterns. In bytes patterns they are not treated specially.
Octal escapes are included in a limited form. If the first digit is a 0, or ifthere are three octal digits, it is considered an octal escape. Otherwise, it isa group reference. As for string literals, octal escapes are always at mostthree digits in length.
Changed in version 3.3:The'\u' and'\U' escape sequences have been added.
The module defines several functions, constants, and an exception. Some of thefunctions are simplified versions of the full featured methods for compiledregular expressions. Most non-trivial applications always use the compiledform.
Compile a regular expression pattern into a regular expression object, whichcan be used for matching using itsmatch() andsearch() methods,described below.
The expression’s behaviour can be modified by specifying aflags value.Values can be any of the following variables, combined using bitwise OR (the| operator).
The sequence
prog=re.compile(pattern)result=prog.match(string)
is equivalent to
result=re.match(pattern,string)
but usingre.compile() and saving the resulting regular expressionobject for reuse is more efficient when the expression will be used severaltimes in a single program.
Note
The compiled versions of the most recent patterns passed tore.match(),re.search() orre.compile() are cached, soprograms that use only a few regular expressions at a time needn’t worryabout compiling regular expressions.
Make\w,\W,\b,\B,\d,\D,\s and\Sperform ASCII-only matching instead of full Unicode matching. This is onlymeaningful for Unicode patterns, and is ignored for byte patterns.
Note that for backward compatibility, there.U flag stillexists (as well as its synonymre.UNICODE and its embeddedcounterpart(?u)), but these are redundant in Python 3 sincematches are Unicode by default for strings (and Unicode matchingisn’t allowed for bytes).
Display debug information about compiled expression.
Perform case-insensitive matching; expressions like[A-Z] will matchlowercase letters, too. This is not affected by the current localeand works for Unicode characters as expected.
Make\w,\W,\b,\B,\s and\S dependent on thecurrent locale. The use of this flag is discouraged as the locale mechanismis very unreliable, and it only handles one “culture” at a time anyway;you should use Unicode matching instead, which is the default in Python 3for Unicode (str) patterns.
When specified, the pattern character'^' matches at the beginning of thestring and at the beginning of each line (immediately following each newline);and the pattern character'$' matches at the end of the string and at theend of each line (immediately preceding each newline). By default,'^'matches only at the beginning of the string, and'$' only at the end of thestring and immediately before the newline (if any) at the end of the string.
Make the'.' special character match any character at all, including anewline; without this flag,'.' will match anythingexcept a newline.
This flag allows you to write regular expressions that look nicer. Whitespacewithin the pattern is ignored, except when in a character class or preceded byan unescaped backslash, and, when a line contains a'#' neither in acharacter class or preceded by an unescaped backslash, all characters from theleftmost such'#' through the end of the line are ignored.
That means that the two following regular expression objects that match adecimal number are functionally equal:
a=re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""",re.X)b=re.compile(r"\d+\.\d*")
Scan throughstring looking for a location where the regular expressionpattern produces a match, and return a correspondingmatch object. ReturnNone if no position in the string matches thepattern; note that this is different from finding a zero-length match at somepoint in the string.
If zero or more characters at the beginning ofstring match the regularexpressionpattern, return a correspondingmatch object. ReturnNone if the string does not match the pattern;note that this is different from a zero-length match.
Note that even inMULTILINE mode,re.match() will only matchat the beginning of the string and not at the beginning of each line.
If you want to locate a match anywhere instring, usesearch()instead (see alsosearch() vs. match()).
Splitstring by the occurrences ofpattern. If capturing parentheses areused inpattern, then the text of all groups in the pattern are also returnedas part of the resulting list. Ifmaxsplit is nonzero, at mostmaxsplitsplits occur, and the remainder of the string is returned as the final elementof the list.
>>>re.split('\W+','Words, words, words.')['Words', 'words', 'words', '']>>>re.split('(\W+)','Words, words, words.')['Words', ', ', 'words', ', ', 'words', '.', '']>>>re.split('\W+','Words, words, words.',1)['Words', 'words, words.']>>>re.split('[a-f]+','0a3B9',flags=re.IGNORECASE)['0', '3', '9']
If there are capturing groups in the separator and it matches at the start ofthe string, the result will start with an empty string. The same holds forthe end of the string:
>>>re.split('(\W+)','...words, words...')['', '...', 'words', ', ', 'words', '...', '']
That way, separator components are always found at the same relativeindices within the result list.
Note thatsplit will never split a string on an empty pattern match.For example:
>>>re.split('x*','foo')['foo']>>>re.split("(?m)^$","foo\n\nbar\n")['foo\n\nbar\n']
Changed in version 3.1:Added the optional flags argument.
Return all non-overlapping matches ofpattern instring, as a list ofstrings. Thestring is scanned left-to-right, and matches are returned inthe order found. If one or more groups are present in the pattern, return alist of groups; this will be a list of tuples if the pattern has more thanone group. Empty matches are included in the result unless they touch thebeginning of another match.
Return aniterator yieldingmatch objects overall non-overlapping matches for the REpattern instring. Thestringis scanned left-to-right, and matches are returned in the order found. Emptymatches are included in the result unless they touch the beginning of anothermatch.
Return the string obtained by replacing the leftmost non-overlapping occurrencesofpattern instring by the replacementrepl. If the pattern isn’t found,string is returned unchanged.repl can be a string or a function; if it isa string, any backslash escapes in it are processed. That is,\n isconverted to a single newline character,\r is converted to a carriage return, andso forth. Unknown escapes such as\j are left alone. Backreferences, suchas\6, are replaced with the substring matched by group 6 in the pattern.For example:
>>>re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',...r'static PyObject*\npy_\1(void)\n{',...'def myfunc():')'static PyObject*\npy_myfunc(void)\n{'
Ifrepl is a function, it is called for every non-overlapping occurrence ofpattern. The function takes a single match object argument, and returns thereplacement string. For example:
>>>defdashrepl(matchobj):...ifmatchobj.group(0)=='-':return' '...else:return'-'>>>re.sub('-{1,2}',dashrepl,'pro----gram-files')'pro--gram files'>>>re.sub(r'\sAND\s',' & ','Baked Beans And Spam',flags=re.IGNORECASE)'Baked Beans & Spam'
The pattern may be a string or an RE object.
The optional argumentcount is the maximum number of pattern occurrences to bereplaced;count must be a non-negative integer. If omitted or zero, alloccurrences will be replaced. Empty matches for the pattern are replaced onlywhen not adjacent to a previous match, sosub('x*','-','abc') returns'-a-b-c-'.
In string-typerepl arguments, in addition to the character escapes andbackreferences described above,\g<name> will use the substring matched by the group namedname, asdefined by the(?P<name>...) syntax.\g<number> uses the correspondinggroup number;\g<2> is therefore equivalent to\2, but isn’t ambiguousin a replacement such as\g<2>0.\20 would be interpreted as areference to group 20, not a reference to group 2 followed by the literalcharacter'0'. The backreference\g<0> substitutes in the entiresubstring matched by the RE.
Changed in version 3.1:Added the optional flags argument.
Perform the same operation assub(), but return a tuple(new_string,number_of_subs_made).
Changed in version 3.1:Added the optional flags argument.
Escape all the characters in pattern except ASCII letters, numbers and'_'.This is useful if you want to match an arbitrary literal string that mayhave regular expression metacharacters in it.
Changed in version 3.3:The'_' character is no longer escaped.
Clear the regular expression cache.
Exception raised when a string passed to one of the functions here is not avalid regular expression (for example, it might contain unmatched parentheses)or when some other error occurs during compilation or matching. It is never anerror if a string contains no match for a pattern.
Compiled regular expression objects support the following methods andattributes:
Scan throughstring looking for a location where this regular expressionproduces a match, and return a correspondingmatch object. ReturnNone if no position in the string matches thepattern; note that this is different from finding a zero-length match at somepoint in the string.
The optional second parameterpos gives an index in the string where thesearch is to start; it defaults to0. This is not completely equivalent toslicing the string; the'^' pattern character matches at the real beginningof the string and at positions just after a newline, but not necessarily at theindex where the search is to start.
The optional parameterendpos limits how far the string will be searched; itwill be as if the string isendpos characters long, so only the charactersfrompos toendpos-1 will be searched for a match. Ifendpos is lessthanpos, no match will be found; otherwise, ifrx is a compiled regularexpression object,rx.search(string,0,50) is equivalent torx.search(string[:50],0).
>>>pattern=re.compile("d")>>>pattern.search("dog")# Match at index 0<_sre.SRE_Match object at ...>>>>pattern.search("dog",1)# No match; search doesn't include the "d"
If zero or more characters at thebeginning ofstring match this regularexpression, return a correspondingmatch object.ReturnNone if the string does not match the pattern; note that this isdifferent from a zero-length match.
The optionalpos andendpos parameters have the same meaning as for thesearch() method.
>>>pattern=re.compile("o")>>>pattern.match("dog")# No match as "o" is not at the start of "dog".>>>pattern.match("dog",1)# Match as "o" is the 2nd character of "dog".<_sre.SRE_Match object at ...>
If you want to locate a match anywhere instring, usesearch() instead (see alsosearch() vs. match()).
Similar to thefindall() function, using the compiled pattern, butalso accepts optionalpos andendpos parameters that limit the searchregion like formatch().
Similar to thefinditer() function, using the compiled pattern, butalso accepts optionalpos andendpos parameters that limit the searchregion like formatch().
The regex matching flags. This is a combination of the flags given tocompile(), any(?...) inline flags in the pattern, and implicitflags such asUNICODE if the pattern is a Unicode string.
The number of capturing groups in the pattern.
A dictionary mapping any symbolic group names defined by(?P<id>) to groupnumbers. The dictionary is empty if no symbolic groups were used in thepattern.
The pattern string from which the RE object was compiled.
Match objects always have a boolean value ofTrue.Sincematch() andsearch() returnNonewhen there is no match, you can test whether there was a match with a simpleif statement:
match=re.search(pattern,string)ifmatch:process(match)
Match objects support the following methods and attributes:
Return the string obtained by doing backslash substitution on the templatestringtemplate, as done by thesub() method.Escapes such as\n are converted to the appropriate characters,and numeric backreferences (\1,\2) and named backreferences(\g<1>,\g<name>) are replaced by the contents of thecorresponding group.
Returns one or more subgroups of the match. If there is a single argument, theresult is a single string; if there are multiple arguments, the result is atuple with one item per argument. Without arguments,group1 defaults to zero(the whole match is returned). If agroupN argument is zero, the correspondingreturn value is the entire matching string; if it is in the inclusive range[1..99], it is the string matching the corresponding parenthesized group. If agroup number is negative or larger than the number of groups defined in thepattern, anIndexError exception is raised. If a group is contained in apart of the pattern that did not match, the corresponding result isNone.If a group is contained in a part of the pattern that matched multiple times,the last match is returned.
>>>m=re.match(r"(\w+) (\w+)","Isaac Newton, physicist")>>>m.group(0)# The entire match'Isaac Newton'>>>m.group(1)# The first parenthesized subgroup.'Isaac'>>>m.group(2)# The second parenthesized subgroup.'Newton'>>>m.group(1,2)# Multiple arguments give us a tuple.('Isaac', 'Newton')
If the regular expression uses the(?P<name>...) syntax, thegroupNarguments may also be strings identifying groups by their group name. If astring argument is not used as a group name in the pattern, anIndexErrorexception is raised.
A moderately complicated example:
>>>m=re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)","Malcolm Reynolds")>>>m.group('first_name')'Malcolm'>>>m.group('last_name')'Reynolds'
Named groups can also be referred to by their index:
>>>m.group(1)'Malcolm'>>>m.group(2)'Reynolds'
If a group matches multiple times, only the last match is accessible:
>>>m=re.match(r"(..)+","a1b2c3")# Matches 3 times.>>>m.group(1)# Returns only the last match.'c3'
Return a tuple containing all the subgroups of the match, from 1 up to howevermany groups are in the pattern. Thedefault argument is used for groups thatdid not participate in the match; it defaults toNone.
For example:
>>>m=re.match(r"(\d+)\.(\d+)","24.1632")>>>m.groups()('24', '1632')
If we make the decimal place and everything after it optional, not all groupsmight participate in the match. These groups will default toNone unlessthedefault argument is given:
>>>m=re.match(r"(\d+)\.?(\d+)?","24")>>>m.groups()# Second group defaults to None.('24', None)>>>m.groups('0')# Now, the second group defaults to '0'.('24', '0')
Return a dictionary containing all thenamed subgroups of the match, keyed bythe subgroup name. Thedefault argument is used for groups that did notparticipate in the match; it defaults toNone. For example:
>>>m=re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)","Malcolm Reynolds")>>>m.groupdict(){'first_name': 'Malcolm', 'last_name': 'Reynolds'}
Return the indices of the start and end of the substring matched bygroup;group defaults to zero (meaning the whole matched substring). Return-1 ifgroup exists but did not contribute to the match. For a match objectm, anda groupg that did contribute to the match, the substring matched by groupg(equivalent tom.group(g)) is
m.string[m.start(g):m.end(g)]
Note thatm.start(group) will equalm.end(group) ifgroup matched anull string. For example, afterm=re.search('b(c?)','cba'),m.start(0) is 1,m.end(0) is 2,m.start(1) andm.end(1) are both2, andm.start(2) raises anIndexError exception.
An example that will removeremove_this from email addresses:
>>>email="tony@tiremove_thisger.net">>>m=re.search("remove_this",email)>>>email[:m.start()]+email[m.end():]'tony@tiger.net'
For a matchm, return the 2-tuple(m.start(group),m.end(group)). Notethat ifgroup did not contribute to the match, this is(-1,-1).group defaults to zero, the entire match.
The value ofpos which was passed to thesearch() ormatch() method of aregex object. This isthe index into the string at which the RE engine started looking for a match.
The value ofendpos which was passed to thesearch() ormatch() method of aregex object. This isthe index into the string beyond which the RE engine will not go.
The integer index of the last matched capturing group, orNone if no groupwas matched at all. For example, the expressions(a)b,((a)(b)), and((ab)) will havelastindex==1 if applied to the string'ab', whilethe expression(a)(b) will havelastindex==2, if applied to the samestring.
The name of the last matched capturing group, orNone if the group didn’thave a name, or if no group was matched at all.
In this example, we’ll use the following helper function to display matchobjects a little more gracefully:
defdisplaymatch(match):ifmatchisNone:returnNonereturn'<Match: %r, groups=%r>'%(match.group(),match.groups())
Suppose you are writing a poker program where a player’s hand is represented asa 5-character string with each character representing a card, “a” for ace, “k”for king, “q” for queen, “j” for jack, “t” for 10, and “2” through “9”representing the card with that value.
To see if a given string is a valid hand, one could do the following:
>>>valid=re.compile(r"^[a2-9tjqk]{5}$")>>>displaymatch(valid.match("akt5q"))# Valid."<Match: 'akt5q', groups=()>">>>displaymatch(valid.match("akt5e"))# Invalid.>>>displaymatch(valid.match("akt"))# Invalid.>>>displaymatch(valid.match("727ak"))# Valid."<Match: '727ak', groups=()>"
That last hand,"727ak", contained a pair, or two of the same valued cards.To match this with a regular expression, one could use backreferences as such:
>>>pair=re.compile(r".*(.).*\1")>>>displaymatch(pair.match("717ak"))# Pair of 7s."<Match: '717', groups=('7',)>">>>displaymatch(pair.match("718ak"))# No pairs.>>>displaymatch(pair.match("354aa"))# Pair of aces."<Match: '354aa', groups=('a',)>"
To find out what card the pair consists of, one could use thegroup() method of the match object in the following manner:
>>>pair.match("717ak").group(1)'7'# Error because re.match() returns None, which doesn't have a group() method:>>>pair.match("718ak").group(1)Traceback (most recent call last): File"<pyshell#23>", line1, in<module>re.match(r".*(.).*\1","718ak").group(1)AttributeError:'NoneType' object has no attribute 'group'>>>pair.match("354aa").group(1)'a'
Python does not currently have an equivalent toscanf(). Regularexpressions are generally more powerful, though also more verbose, thanscanf() format strings. The table below offers some more-or-lessequivalent mappings betweenscanf() format tokens and regularexpressions.
| scanf() Token | Regular Expression |
|---|---|
| %c | . |
| %5c | .{5} |
| %d | [-+]?\d+ |
| %e,%E,%f,%g | [-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)? |
| %i | [-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+) |
| %o | [-+]?[0-7]+ |
| %s | \S+ |
| %u | \d+ |
| %x,%X | [-+]?(0[xX])?[\dA-Fa-f]+ |
To extract the filename and numbers from a string like
/usr/sbin/sendmail-0errors,4warnings
you would use ascanf() format like
%s-%derrors,%dwarnings
The equivalent regular expression would be
(\S+)-(\d+)errors,(\d+)warnings
Python offers two different primitive operations based on regular expressions:re.match() checks for a match only at the beginning of the string, whilere.search() checks for a match anywhere in the string (this is what Perldoes by default).
For example:
>>>re.match("c","abcdef")# No match>>>re.search("c","abcdef")# Match<_sre.SRE_Match object at ...>
Regular expressions beginning with'^' can be used withsearch() torestrict the match at the beginning of the string:
>>>re.match("c","abcdef")# No match>>>re.search("^c","abcdef")# No match>>>re.search("^a","abcdef")# Match<_sre.SRE_Match object at ...>
Note however that inMULTILINE modematch() only matches at thebeginning of the string, whereas usingsearch() with a regular expressionbeginning with'^' will match at the beginning of each line.
>>>re.match('X','A\nB\nX',re.MULTILINE)# No match>>>re.search('^X','A\nB\nX',re.MULTILINE)# Match<_sre.SRE_Match object at ...>
split() splits a string into a list delimited by the passed pattern. Themethod is invaluable for converting textual data into data structures that can beeasily read and modified by Python as demonstrated in the following example thatcreates a phonebook.
First, here is the input. Normally it may come from a file, here we are usingtriple-quoted string syntax:
>>>text="""Ross McFluff: 834.345.1254 155 Elm Street......Ronald Heathmore: 892.345.3428 436 Finley Avenue...Frank Burger: 925.541.7625 662 South Dogwood Way.........Heather Albrecht: 548.326.4584 919 Park Place"""
The entries are separated by one or more newlines. Now we convert the stringinto a list with each nonempty line having its own entry:
>>>entries=re.split("\n+",text)>>>entries['Ross McFluff: 834.345.1254 155 Elm Street','Ronald Heathmore: 892.345.3428 436 Finley Avenue','Frank Burger: 925.541.7625 662 South Dogwood Way','Heather Albrecht: 548.326.4584 919 Park Place']
Finally, split each entry into a list with first name, last name, telephonenumber, and address. We use themaxsplit parameter ofsplit()because the address has spaces, our splitting pattern, in it:
>>>[re.split(":? ",entry,3)forentryinentries][['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]
The:? pattern matches the colon after the last name, so that it does notoccur in the result list. With amaxsplit of4, we could separate thehouse number from the street name:
>>>[re.split(":? ",entry,4)forentryinentries][['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]
sub() replaces every occurrence of a pattern with a string or theresult of a function. This example demonstrates usingsub() witha function to “munge” text, or randomize the order of all the charactersin each word of a sentence except for the first and last characters:
>>>defrepl(m):...inner_word=list(m.group(2))...random.shuffle(inner_word)...returnm.group(1)+"".join(inner_word)+m.group(3)>>>text="Professor Abdolmalek, please report your absences promptly.">>>re.sub(r"(\w)(\w+)(\w)",repl,text)'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'>>>re.sub(r"(\w)(\w+)(\w)",repl,text)'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'
findall() matchesall occurrences of a pattern, not just the firstone assearch() does. For example, if one was a writer and wanted tofind all of the adverbs in some text, he or she might usefindall() inthe following manner:
>>>text="He was carefully disguised but captured quickly by police.">>>re.findall(r"\w+ly",text)['carefully', 'quickly']
If one wants more information about all matches of a pattern than the matchedtext,finditer() is useful as it providesmatch objects instead of strings. Continuing with the previous example, ifone was a writer who wanted to find all of the adverbsand their positions insome text, he or she would usefinditer() in the following manner:
>>>text="He was carefully disguised but captured quickly by police.">>>forminre.finditer(r"\w+ly",text):...print('%02d-%02d: %s'%(m.start(),m.end(),m.group(0)))07-16: carefully40-47: quickly
Raw string notation (r"text") keeps regular expressions sane. Without it,every backslash ('\') in a regular expression would have to be prefixed withanother one to escape it. For example, the two following lines of code arefunctionally identical:
>>>re.match(r"\W(.)\1\W"," ff ")<_sre.SRE_Match object at ...>>>>re.match("\\W(.)\\1\\W"," ff ")<_sre.SRE_Match object at ...>
When one wants to match a literal backslash, it must be escaped in the regularexpression. With raw string notation, this meansr"\\". Without raw stringnotation, one must use"\\\\", making the following lines of codefunctionally identical:
>>>re.match(r"\\",r"\\")<_sre.SRE_Match object at ...>>>>re.match("\\\\",r"\\")<_sre.SRE_Match object at ...>
Atokenizer or scanneranalyzes a string to categorize groups of characters. This is a useful firststep in writing a compiler or interpreter.
The text categories are specified with regular expressions. The technique isto combine those into a single master regular expression and to loop oversuccessive matches:
importcollectionsimportreToken=collections.namedtuple('Token',['typ','value','line','column'])deftokenize(s):keywords={'IF','THEN','ENDIF','FOR','NEXT','GOSUB','RETURN'}token_specification=[('NUMBER',r'\d+(\.\d*)?'),# Integer or decimal number('ASSIGN',r':='),# Assignment operator('END',r';'),# Statement terminator('ID',r'[A-Za-z]+'),# Identifiers('OP',r'[+*\/\-]'),# Arithmetic operators('NEWLINE',r'\n'),# Line endings('SKIP',r'[ \t]'),# Skip over spaces and tabs]tok_regex='|'.join('(?P<%s>%s)'%pairforpairintoken_specification)get_token=re.compile(tok_regex).matchline=1pos=line_start=0mo=get_token(s)whilemoisnotNone:typ=mo.lastgroupiftyp=='NEWLINE':line_start=posline+=1eliftyp!='SKIP':val=mo.group(typ)iftyp=='ID'andvalinkeywords:typ=valyieldToken(typ,val,line,mo.start()-line_start)pos=mo.end()mo=get_token(s,pos)ifpos!=len(s):raiseRuntimeError('Unexpected character %r on line %d'%(s[pos],line))statements=''' IF quantity THEN total := total + price * quantity; tax := price * 0.05; ENDIF;'''fortokenintokenize(statements):print(token)
The tokenizer produces the following output:
Token(typ='IF',value='IF',line=2,column=5)Token(typ='ID',value='quantity',line=2,column=8)Token(typ='THEN',value='THEN',line=2,column=17)Token(typ='ID',value='total',line=3,column=9)Token(typ='ASSIGN',value=':=',line=3,column=15)Token(typ='ID',value='total',line=3,column=18)Token(typ='OP',value='+',line=3,column=24)Token(typ='ID',value='price',line=3,column=26)Token(typ='OP',value='*',line=3,column=32)Token(typ='ID',value='quantity',line=3,column=34)Token(typ='END',value=';',line=3,column=42)Token(typ='ID',value='tax',line=4,column=9)Token(typ='ASSIGN',value=':=',line=4,column=13)Token(typ='ID',value='price',line=4,column=16)Token(typ='OP',value='*',line=4,column=22)Token(typ='NUMBER',value='0.05',line=4,column=24)Token(typ='END',value=';',line=4,column=28)Token(typ='ENDIF',value='ENDIF',line=5,column=5)Token(typ='END',value=';',line=5,column=10)
6.1.string — Common string operations
6.3.difflib — Helpers for computing deltas
Enter search terms or a module, class or function name.