re
--- 正規表示式 (regular expression) 操作¶
原始碼:Lib/re/
此模組提供類似於 Perl 中正規表示式的配對操作。
被搜尋的模式 (pattern) 與字串可以是 Unicode 字串 (str
),也可以是 8-bit 字串 (bytes
)。然而,Unicode 字串和 8-bit 字串不能混用:也就是,你不能用 byte 模式配對 Unicode 字串,反之亦然;同樣地,替換時,用來替換的字串必須與模式和搜尋字串是相同的型別 (type)。
正規表示式使用反斜線字元 ('\'
) 表示特別的形式,或是使用特殊字元而不呼叫它們的特殊意義。這與 Python 在字串文本 (literal) 中,為了一樣的目的使用同一個字元的目的相衝突;舉例來說,為了配對一個反斜線文字,一個人可能需要寫'\\\\'
當作模式字串,因為正規表示式必須是\\
,而且每個反斜線在一個普通的 Python 字串文本中必須表示為\\
。另外,請注意在 Python 的字串文本中使用反斜線的任何無效跳脫序列目前會產生一個SyntaxWarning
,而在未來這會變成一個SyntaxError
。儘管它對正規表示式是一個有效的跳脫序列,這種行為也會發生。
解決方法是對正規表示式模式使用 Python 的原始字串符號;反斜線在一個以'r'
為前綴的字串文本中不會被用任何特別的方式處理。所以r"\n"
是一個兩個字元的字串,包含'\'
和'n'
,同時"\n"
是一個單個字元的字串,包含一個換行符號。通常模式在 Python 程式中會使用這個原始字串符號表示。
請務必注意到大部分的正規表示式操作是可以在模組層級的函式和compiled regular expressions 中的方法使用的。這些函式是個捷徑且讓你不需要先編譯一個正規表示式物件,但是會缺少一些微調參數。
正規表示式語法¶
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[Frie09],or almost any textbook about compiler construction.
A brief explanation of the format of regular expressions follows. For furtherinformation and a gentler presentation, consult the如何使用正規表示式.
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.
Repetition operators or quantifiers (*
,+
,?
,{m,n}
, etc) cannot bedirectly nested. This avoids ambiguity with the non-greedy modifier suffix?
, and with other modifiers in other implementations. To apply a secondrepetition to an inner repetition, parentheses may be used. For example,the expression(?:a{6})*
matches any multiple of six'a'
characters.
The special characters are:
.
(Dot.) In the default mode, this matches any character except a newline. Ifthe
DOTALL
flag has been specified, this matches any characterincluding a newline.(?s:.)
matches any character regardless of flags.
^
(Caret.) Matches the start of the string, and in
MULTILINE
mode alsomatches immediately after each newline.
$
Matches the end of the string or just before the newline at the end of thestring, and in
MULTILINE
mode also matches before a newline.foo
matches both 'foo' and 'foobar', while the regular expressionfoo$
matchesonly 'foo'. More interestingly, searching forfoo.$
in'foo1\nfoo2\n'
matches 'foo2' normally, but 'foo1' inMULTILINE
mode; searching fora single$
in'foo\n'
will find two (empty) matches: one just beforethe newline, and one at the end of the string.
*
Causes the resulting RE to match 0 or more repetitions of the preceding RE, asmany repetitions as are possible.
ab*
will match 'a', 'ab', or 'a' followedby any number of 'b's.
+
Causes the resulting RE to match 1 or more repetitions of the preceding RE.
ab+
will match 'a' followed by any non-zero number of 'b's; it will notmatch just 'a'.
?
Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
ab?
will match either 'a' or 'ab'.
*?
,+?
,??
The
'*'
,'+'
, and'?'
quantifiers are allgreedy; they matchas much text as possible. Sometimes this behaviour isn't desired; if the RE<.*>
is matched against'<a>b<c>'
, it will match the entirestring, and not just'<a>'
. Adding?
after the quantifier makes itperform the match innon-greedy orminimal fashion; asfewcharacters as possible will be matched. Using the RE<.*?>
will matchonly'<a>'
.
*+
,++
,?+
Like the
'*'
,'+'
, and'?'
quantifiers, those where'+'
isappended also match as many times as possible.However, unlike the true greedy quantifiers, these do not allowback-tracking when the expression following it fails to match.These are known aspossessive quantifiers.For example,a*a
will match'aaaa'
because thea*
will matchall 4'a'
s, but, when the final'a'
is encountered, theexpression is backtracked so that in the end thea*
ends up matching3'a'
s total, and the fourth'a'
is matched by the final'a'
.However, whena*+a
is used to match'aaaa'
, thea*+
willmatch all 4'a'
, but when the final'a'
fails to find any morecharacters to match, the expression cannot be backtracked and will thusfail to match.x*+
,x++
andx?+
are equivalent to(?>x*)
,(?>x+)
and(?>x?)
correspondingly.在 3.11 版被加入.
{m}
Specifies that exactlym copies of the previous RE should be matched; fewermatches cause the entire RE not to match. For example,
a{6}
will matchexactly six'a'
characters, but not five.{m,n}
Causes the resulting RE to match fromm ton repetitions of the precedingRE, attempting to match as many repetitions as possible. For example,
a{3,5}
will match from 3 to 5'a'
characters. Omittingm specifies alower bound of zero, and omittingn specifies an infinite upper bound. As anexample,a{4,}b
will match'aaaab'
or a thousand'a'
charactersfollowed by a'b'
, but not'aaab'
. The comma may not be omitted or themodifier would be confused with the previously described form.{m,n}?
Causes the resulting RE to match fromm ton repetitions of the precedingRE, attempting to match asfew repetitions as possible. This is thenon-greedy version of the previous quantifier. For example, on the6-character string
'aaaaaa'
,a{3,5}
will match 5'a'
characters,whilea{3,5}?
will only match 3 characters.{m,n}+
Causes the resulting RE to match fromm ton repetitions of thepreceding RE, attempting to match as many repetitions as possiblewithout establishing any backtracking points.This is the possessive version of the quantifier above.For example, on the 6-character string
'aaaaaa'
,a{3,5}+aa
attempt to match 5'a'
characters, then, requiring 2 more'a'
s,will need more characters than available and thus fail, whilea{3,5}aa
will match witha{3,5}
capturing 5, then 4'a'
sby backtracking and then the final 2'a'
s are matched by the finalaa
in the pattern.x{m,n}+
is equivalent to(?>x{m,n})
.在 3.11 版被加入.
\
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:
Characters can be listed individually, e.g.
[amk]
will match'a'
,'m'
, or'k'
.
Ranges of characters can be indicated by giving two characters and separatingthem by a
'-'
, for example[a-z]
will match any lowercase ASCII letter,[0-5][0-9]
will match all the two-digits numbers from00
to59
, and[0-9A-Fa-f]
will match any hexadecimal digit. If-
is escaped (e.g.[a\-z]
) or if it's placed as the first or last character(e.g.[-a]
or[a-]
), it will match a literal'-'
.Special characters except backslash lose their special meaning inside sets.For example,
[(+*)]
will match any of the literal characters'('
,'+'
,'*'
, or')'
.
Backslash either escapes characters which have special meaning in a setsuch as
'-'
,']'
,'^'
and'\\'
itself or signalsa special sequence which represents a single character such as\xa0
or\n
or a character class such as\w
or\S
(defined below).Note that\b
represents a single "backspace" character,not a word boundary as outside a set, and numeric escapessuch as\1
are always octal escapes, not group references.Special sequences which do not match a single character such as\A
and\Z
are not allowed.
Characters that are not within a range can be matched bycomplementingthe set. If the first character of the set is
'^'
, all the charactersthat arenot in the set will be matched. For example,[^5]
will matchany character except'5'
, and[^^]
will match any character except'^'
.^
has no special meaning if it's not the first character inthe set.To match a literal
']'
inside a set, precede it with a backslash, orplace it at the beginning of the set. For example, both[()[\]{}]
and[]()[{}]
will match a right bracket, as well as left bracket, braces,and parentheses.
Support of nested sets and set operations as inUnicode TechnicalStandard #18 might be added in the future. This would change thesyntax, so to facilitate this change a
FutureWarning
will be raisedin ambiguous cases for the time being.That includes sets starting with a literal'['
or containing literalcharacter sequences'--'
,'&&'
,'~~'
, and'||'
. Toavoid a warning escape them with a backslash.
在 3.7 版的變更:
FutureWarning
is raised if a character set contains constructsthat will change semantically in the future.
|
A|B
, whereA andB can be arbitrary REs, creates a regular expression thatwill match eitherA orB. An arbitrary number of REs can be separated by the'|'
in this way. This can be used inside groups (see below) as well. Asthe target string is scanned, REs separated by'|'
are tried from left toright. When one pattern completely matches, that branch is accepted. This meansthat onceA matches,B will not be tested further, even if it wouldproduce a longer overall match. In other words, the'|'
operator is nevergreedy. To match a literal'|'
, use\|
, or enclose it inside acharacter class, as in[|]
.
(...)
Matches whatever regular expression is inside the parentheses, and indicates thestart and end of a group; the contents of a group can be retrieved after a matchhas been performed, and can be matched later in the string with the
\number
special sequence, described below. To match the literals'('
or')'
,use\(
or\)
, or enclose them inside a character class:[(]
,[)]
.
(?...)
This is an extension notation (a
'?'
following a'('
is not meaningfulotherwise). The first character after the'?'
determines what the meaningand further syntax of the construct is. Extensions usually do not create a newgroup;(?P<name>...)
is the only exception to this rule. Following are thecurrently supported extensions.(?aiLmsux)
(One or more letters from the set
'a'
,'i'
,'L'
,'m'
,'s'
,'u'
,'x'
.)The group matches the empty string;the letters set the corresponding flags for the entire regular expression:re.A
(ASCII-only matching)re.I
(ignore case)re.L
(locale dependent)re.M
(multi-line)re.S
(dot matches all)re.U
(Unicode matching)re.X
(verbose)
(The flags are described in模組內容.)This is useful if you wish to include the flags as part of theregular expression, instead of passing aflag argument to the
re.compile()
function.Flags should be used first in the expression string.在 3.11 版的變更:This construction can only be used at the start of the expression.
(?:...)
A non-capturing version of regular parentheses. Matches whatever regularexpression is inside the parentheses, but the substring matched by the groupcannot be retrieved after performing a match or referenced later in thepattern.
(?aiLmsux-imsx:...)
(Zero or more letters from the set
'a'
,'i'
,'L'
,'m'
,'s'
,'u'
,'x'
,optionally followed by'-'
followed byone or more letters from the'i'
,'m'
,'s'
,'x'
.)The letters set or remove the corresponding flags for the part of the expression:re.A
(ASCII-only matching)re.I
(ignore case)re.L
(locale dependent)re.M
(multi-line)re.S
(dot matches all)re.U
(Unicode matching)re.X
(verbose)
(The flags are described in模組內容.)
The letters
'a'
,'L'
and'u'
are mutually exclusive when usedas inline flags, so they can't be combined or follow'-'
. Instead,when one of them appears in an inline group, it overrides the matching modein the enclosing group. In Unicode patterns(?a:...)
switches toASCII-only matching, and(?u:...)
switches to Unicode matching(default). In bytes patterns(?L:...)
switches to locale dependentmatching, and(?a:...)
switches to ASCII-only matching (default).This override is only in effect for the narrow inline group, and theoriginal matching mode is restored outside of the group.在 3.6 版被加入.
在 3.7 版的變更:The letters
'a'
,'L'
and'u'
also can be used in a group.(?>...)
Attempts to match
...
as if it was a separate regular expression, andif successful, continues to match the rest of the pattern following it.If the subsequent pattern fails to match, the stack can only be unwoundto a pointbefore the(?>...)
because once exited, the expression,known as anatomic group, has thrown away all stack points withinitself.Thus,(?>.*).
would never match anything because first the.*
would match all characters possible, then, having nothing left to match,the final.
would fail to match.Since there are no stack points saved in the Atomic Group, and there isno stack point before it, the entire expression would thus fail to match.在 3.11 版被加入.
(?P<name>...)
Similar to regular parentheses, but the substring matched by the group isaccessible via the symbolic group namename. Group names must be validPython identifiers, and in
bytes
patterns they can only containbytes in the ASCII range. Each group name must be defined only once withina regular 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
(?P=quote)
(as shown)\1
when processing match objectm
m.group('quote')
m.end('quote')
(etc.)
in a string passed to thereplargument of
re.sub()
\g<quote>
\g<1>
\1
在 3.12 版的變更:In
bytes
patterns, groupname can only contain bytesin the ASCII range (b'\x00'
-b'\x7f'
).
(?P=name)
A backreference to a named group; it matches whatever text was matched by theearlier group namedname.
(?#...)
A comment; the contents of the parentheses are simply ignored.
(?=...)
Matches if
...
matches next, but doesn't consume any of the string. This iscalled alookahead assertion. For example,Isaac(?=Asimov)
will match'Isaac'
only if it's followed by'Asimov'
.
(?!...)
Matches if
...
doesn't match next. This is anegative lookahead assertion.For example,Isaac(?!Asimov)
will match'Isaac'
only if it'snotfollowed by'Asimov'
.
(?<=...)
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 in'abcdef'
, 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(r'(?<=-)\w+','spam-egg')>>>m.group(0)'egg'
在 3.5 版的變更:Added support for group references of fixed length.
(?<!...)
Matches if the current position in the string is not preceded by a match for
...
. This is called anegative lookbehind assertion. Similar topositive lookbehind assertions, the contained pattern must only match strings ofsome fixed length. Patterns which start with negative lookbehind assertions maymatch at the beginning of the string being searched.
(?(id/name)yes-pattern|no-pattern)
Will try to match with
yes-pattern
if the group with givenid orname exists, and withno-pattern
if it doesn't.no-pattern
isoptional and can be omitted. For example,(<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$)
is a poor email matching pattern, whichwill match with'<user@host.com>'
as well as'user@host.com'
, butnot with'<user@host.com'
nor'user@host.com>'
.在 3.12 版的變更:Groupid can only contain ASCII digits.In
bytes
patterns, groupname can only contain bytesin the ASCII range (b'\x00'
-b'\x7f'
).
The special sequences consist of'\'
and a character from the list below.If the ordinary character is not an ASCII digit or an ASCII letter, then theresulting RE will match the second character. For example,\$
matches thecharacter'$'
.
\number
Matches the contents of the group of the same number. Groups are numberedstarting from 1. For example,
(.+)\1
matches'thethe'
or'5555'
,but not'thethe'
(note the space after the group). This special sequencecan only be used to match one of the first 99 groups. If the first digit ofnumber is 0, ornumber is 3 octal digits long, it will not be interpreted asa group match, but as the character with octal valuenumber. Inside the'['
and']'
of a character class, all numeric escapes are treated ascharacters.
\A
Matches only at the start of the string.
\b
Matches the empty string, but only at the beginning or end of a word.A word is defined as a sequence of word characters.Note that formally,
\b
is defined as the boundarybetween a\w
and a\W
character (or vice versa),or between\w
and the beginning or end of the string.This means thatr'\bat\b'
matches'at'
,'at.'
,'(at)'
,and'asatay'
but not'attempt'
or'atlas'
.The default word characters in Unicode (str) patternsare Unicode alphanumerics and the underscore,but this can be changed by using the
ASCII
flag.Word boundaries are determined by the current localeif theLOCALE
flag is used.備註
Inside a character range,
\b
represents the backspace character,for compatibility with Python's string literals.
\B
Matches the empty string,but only when it isnot at the beginning or end of a word.This means that
r'at\B'
matches'athens'
,'atom'
,'attorney'
, but not'at'
,'at.'
, or'at!'
.\B
is the opposite of\b
,so word characters in Unicode (str) patternsare Unicode alphanumerics or the underscore,although this can be changed by using theASCII
flag.Word boundaries are determined by the current localeif theLOCALE
flag is used.備註
Note that
\B
does not match an empty string, which differs fromRE implementations in other programming languages such as Perl.This behavior is kept for compatibility reasons.
\d
- For Unicode (str) patterns:
Matches any Unicode decimal digit(that is, any character in Unicode character category[Nd]).This includes
[0-9]
, and also many other digit characters.Matches
[0-9]
if theASCII
flag is used.- For 8-bit (bytes) patterns:
Matches any decimal digit in the ASCII character set;this is equivalent to
[0-9]
.
\D
Matches any character which is not a decimal digit.This is the opposite of
\d
.Matches
[^0-9]
if theASCII
flag is used.
\s
- For Unicode (str) patterns:
Matches Unicode whitespace characters (as defined by
str.isspace()
).This includes[\t\n\r\f\v]
, and also many other characters, for example thenon-breaking spaces mandated by typography rules in many languages.Matches
[\t\n\r\f\v]
if theASCII
flag is used.- For 8-bit (bytes) patterns:
Matches characters considered whitespace in the ASCII character set;this is equivalent to
[\t\n\r\f\v]
.
\S
Matches any character which is not a whitespace character. This isthe opposite of
\s
.Matches
[^\t\n\r\f\v]
if theASCII
flag is used.
\w
- For Unicode (str) patterns:
Matches Unicode word characters;this includes all Unicode alphanumeric characters(as defined by
str.isalnum()
),as well as the underscore (_
).Matches
[a-zA-Z0-9_]
if theASCII
flag is used.- For 8-bit (bytes) patterns:
Matches characters considered alphanumeric in the ASCII character set;this is equivalent to
[a-zA-Z0-9_]
.If theLOCALE
flag is used,matches characters considered alphanumeric in the current locale and the underscore.
\W
Matches any character which is not a word character.This is the opposite of
\w
.By default, matches non-underscore (_
) charactersfor whichstr.isalnum()
returnsFalse
.Matches
[^a-zA-Z0-9_]
if theASCII
flag is used.If the
LOCALE
flag is used,matches characters which are neither alphanumeric in the current localenor the underscore.
\Z
Matches only at the end of the string.
Most of theescape sequences supported by Pythonstring literals are also accepted by the regular expression parser:
\a \b \f \n\N \r \t \u\U \v \x \\
(Note that\b
is used to represent word boundaries, and means "backspace"only inside character classes.)
'\u'
,'\U'
, and'\N'
escape sequences areonly recognized in Unicode (str) patterns.In bytes patterns they are errors.Unknown escapes of ASCII letters are reservedfor future use and treated as errors.
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.
在 3.3 版的變更:The'\u'
and'\U'
escape sequences have been added.
在 3.6 版的變更:Unknown escapes consisting of'\'
and an ASCII letter now are errors.
在 3.8 版的變更:The'\N{name}'
escape sequence has been added. As in string literals,it expands to the named Unicode character (e.g.'\N{EMDASH}'
).
模組內容¶
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.
旗標¶
在 3.6 版的變更:Flag constants are now instances ofRegexFlag
, which is a subclass ofenum.IntFlag
.
- classre.RegexFlag¶
An
enum.IntFlag
class containing the regex options listed below.在 3.11 版被加入:- added to
__all__
- re.A¶
- re.ASCII¶
Make
\w
,\W
,\b
,\B
,\d
,\D
,\s
and\S
perform ASCII-only matching instead of full Unicode matching. This is onlymeaningful for Unicode (str) patterns, and is ignored for bytes patterns.Corresponds to the inline flag
(?a)
.
- re.DEBUG¶
Display debug information about compiled expression.
No corresponding inline flag.
- re.I¶
- re.IGNORECASE¶
Perform case-insensitive matching;expressions like
[A-Z]
will also match lowercase letters.Full Unicode matching (such asÜ
matchingü
)also works unless theASCII
flagis used to disable non-ASCII matches.The current locale does not change the effect of this flagunless theLOCALE
flag is also used.Corresponds to the inline flag
(?i)
.Note that when the Unicode patterns
[a-z]
or[A-Z]
are used incombination with theIGNORECASE
flag, they will match the 52 ASCIIletters and 4 additional non-ASCII letters: 'İ' (U+0130, Latin capitalletter I with dot above), 'ı' (U+0131, Latin small letter dotless i),'ſ' (U+017F, Latin small letter long s) and 'K' (U+212A, Kelvin sign).If theASCII
flag is used, only letters 'a' to 'z'and 'A' to 'Z' are matched.
- re.L¶
- re.LOCALE¶
Make
\w
,\W
,\b
,\B
and case-insensitive matchingdependent on the current locale.This flag can be used only with bytes patterns.Corresponds to the inline flag
(?L)
.警告
This flag is discouraged; consider Unicode matching instead.The locale mechanism is very unreliableas it only handles one "culture" at a timeand only works with 8-bit locales.Unicode matching is enabled by default for Unicode (str) patternsand it is able to handle different locales and languages.
在 3.7 版的變更:Compiled regular expression objects with the
LOCALE
flagno longer depend on the locale at compile time.Only the locale at matching time affects the result of matching.
- re.M¶
- re.MULTILINE¶
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.Corresponds to the inline flag
(?m)
.
- re.NOFLAG¶
Indicates no flag being applied, the value is
0
. This flag may be usedas a default value for a function keyword argument or as a base value thatwill be conditionally ORed with other flags. Example of use as a defaultvalue:defmyfunc(text,flag=re.NOFLAG):returnre.match(text,flag)
在 3.11 版被加入.
- re.S¶
- re.DOTALL¶
Make the
'.'
special character match any character at all, including anewline; without this flag,'.'
will match anythingexcept a newline.Corresponds to the inline flag
(?s)
.
- re.U¶
- re.UNICODE¶
In Python 3, Unicode characters are matched by defaultfor
str
patterns.This flag is therefore redundant withno effectand is only kept for backward compatibility.See
ASCII
to restrict matching to ASCII characters instead.
- re.X¶
- re.VERBOSE¶
This flag allows you to write regular expressions that look nicer and aremore readable by allowing you to visually separate logical sections of thepattern and add comments. Whitespace within the pattern is ignored, exceptwhen in a character class, or when preceded by an unescaped backslash,or within tokens like
*?
,(?:
or(?P<...>
. For example,(?:
and*?
are not allowed.When a line contains a#
that is not in a character class and is notpreceded by an unescaped backslash, all characters from the leftmost such#
through the end of the line are ignored.This 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*")
Corresponds to the inline flag
(?x)
.
函式¶
- re.compile(pattern,flags=0)¶
將正規表示式模式編譯成正規表示式物件,可以使用它的
match()
、search()
等方法來匹配,如下所述。可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。順序為:
prog=re.compile(pattern)result=prog.match(string)
等價於:
result=re.match(pattern,string)
但是當表示式在單一程式中多次使用時,使用
re.compile()
並保存產生的正規表示式物件以供重複使用會更有效率。備註
傳遞給
re.compile()
之最新模式的編譯版本和模組層級匹配函式都會被快取,因此一次僅使用幾個正規表示式的程式不必去擔心編譯正規表示式。
- re.search(pattern,string,flags=0)¶
掃描string 以尋找正規表示式pattern 產生匹配的第一個位置,並回傳對應的
Match
。如果字串中沒有與模式匹配的位置則回傳None
;請注意,這與在字串中的某個點查找零長度匹配不同。可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。
- re.match(pattern,string,flags=0)¶
如果string 開頭的零個或多個字元與正規表示式pattern 匹配,則回傳對應的
Match
。如果字串與模式不匹配,則回傳None
;請注意,這與零長度匹配不同。請注意,即使在
MULTILINE
模式 (mode) 下,re.match()
只會於字串的開頭匹配,而非每行的開頭。如果你想在string 中的任何位置找到匹配項,請使用
search()
(另請參閱search() vs. match())。可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。
- re.fullmatch(pattern,string,flags=0)¶
如果整個string 與正規表示式pattern 匹配,則回傳對應的
Match
。如果字串與模式不匹配,則回傳None
;請注意,這與零長度匹配不同。可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。在 3.4 版被加入.
- re.split(pattern,string,maxsplit=0,flags=0)¶
依pattern 的出現次數拆分string。如果在pattern 中使用捕獲括號,則模式中所有群組的文字也會作為結果串列的一部分回傳。如果maxsplit 非零,則最多發生maxsplit 次拆分,並且字串的其餘部分會作為串列的最終元素回傳。
>>>re.split(r'\W+','Words, words, words.')['Words', 'words', 'words', '']>>>re.split(r'(\W+)','Words, words, words.')['Words', ', ', 'words', ', ', 'words', '.', '']>>>re.split(r'\W+','Words, words, words.',maxsplit=1)['Words', 'words, words.']>>>re.split('[a-f]+','0a3B9',flags=re.IGNORECASE)['0', '3', '9']
如果分隔符號中有捕獲群組並且它在字串的開頭匹配,則結果將以空字串開頭。這同樣適用於字串的結尾:
>>>re.split(r'(\W+)','...words, words...')['', '...', 'words', ', ', 'words', '...', '']
如此一來,分隔符號元件始終可以在結果串列中的相同相對索引處找到。
Adjacent empty matches are not possible, but an empty match can occurimmediately after a non-empty match.
>>>re.split(r'\b','Words, words, words.')['', 'Words', ', ', 'words', ', ', 'words', '.']>>>re.split(r'\W*','...words...')['', '', 'w', 'o', 'r', 'd', 's', '', '']>>>re.split(r'(\W*)','...words...')['', '...', '', '', 'w', '', 'o', '', 'r', '', 'd', '', 's', '...', '', '', '']
可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。在 3.1 版的變更:新增可選的旗標引數。
在 3.7 版的變更:新增了對可以匹配空字串之模式進行拆分的支援。
在 3.13 版之後被棄用:將maxsplit 和flags 作為位置引數傳遞的用法已被棄用。在未來的 Python 版本中,它們將會是僅限關鍵字參數。
- re.findall(pattern,string,flags=0)¶
以字串或元組串列的形式回傳string 中pattern 的所有非重疊匹配項。從左到右掃描string,並按找到的順序回傳符合項目。結果中會包含空匹配項。
結果取決於模式中捕獲群組的數量。如果沒有群組,則回傳與整個模式匹配的字串串列。如果恰好存在一個群組,則回傳與該群組匹配的字串串列。如果存在多個群組,則回傳與群組匹配的字串元組串列。非捕獲群組則不影響結果的形式。
>>>re.findall(r'\bf[a-z]*','which foot or hand fell fastest')['foot', 'fell', 'fastest']>>>re.findall(r'(\w+)=(\d+)','set width=20 and height=10')[('width', '20'), ('height', '10')]
可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。在 3.7 版的變更:非空匹配現在可以剛好在前一個空匹配的後面開始。
- re.finditer(pattern,string,flags=0)¶
回傳一個iterator,在string 中的 REpattern 的所有非重疊匹配上 yield
Match
物件。從左到右掃描string,並按找到的順序回傳匹配項目。結果中包含空匹配項。可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。在 3.7 版的變更:非空匹配現在可以剛好在前一個空匹配的後面開始。
- re.sub(pattern,repl,string,count=0,flags=0)¶
回傳透過以替換repl 取代string 中最左邊不重疊出現的pattern 所獲得的字串。如果未找到該模式,則不改變string 並回傳。repl 可以是字串或函式;如果它是字串,則處理其中的任何反斜線轉義。也就是說
\n
會被轉換為單一換行符、\r
會被轉換為回車符 (carriage return) 等等。ASCII 字母的未知轉義符會被保留以供將來使用並被視為錯誤。其他未知轉義符例如\&
會被單獨保留。例如\6
的反向參照將被替換為模式中第 6 組匹配的子字串。例如:>>>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{'
如果repl 是一個函式,則pattern 的每個不重疊出現之處都會呼叫它。此函式接收單一
Match
引數,並回傳替換字串。例如:>>>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'
此模式可以是字串或
Pattern
。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.
Adjacent empty matches are not possible, but an empty match can occurimmediately after a non-empty match.As a result,
sub('x*','-','abxd')
returns'-a-b--d-'
instead of'-a-b-d-'
.在字串型別repl 引數中,除了上述字元轉義和反向參照之外,
\g<name>
將使用名為name
的群組所匹配到的子字串,如(?P<name>...)
所定義的語法。\g<number>
使用對應的群組編號;因此\g<2>
等價於\2
,但在諸如\g<2>0
之類的替換中並非模糊不清 (isn't ambiguous)。\20
將被直譯為對群組 20 的參照,而不是對後面跟著字面字元'0'
的群組 2 的參照。反向參照\g<0>
會取代以 RE 所匹配到的整個子字串。可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。在 3.1 版的變更:新增可選的旗標引數。
在 3.5 版的變更:不匹配的群組將被替換為空字串。
在 3.6 版的變更:在由
'\'
和一個 ASCII 字母組成之pattern 中的未知轉義符現在為錯誤。在 3.7 版的變更:Unknown escapes inrepl consisting of
'\'
and an ASCII letternow are errors.An empty match can occur immediately after a non-empty match.在 3.12 版的變更:群組id 只能包含 ASCII 數字。在
bytes
替換字串中,群組name 只能包含 ASCII 範圍內的位元組 (b'\x00'
-b'\x7f'
)。在 3.13 版之後被棄用:將count 和flags 作為位置引數傳遞的用法已被棄用。在未來的 Python 版本中,它們將會是僅限關鍵字參數。
- re.subn(pattern,repl,string,count=0,flags=0)¶
執行與
sub()
相同的操作,但回傳一個元組(new_string,number_of_subs_made)
。可以透過指定flags 值來修改運算式的行為,值可以是任何flags 變數,使用位元 OR(bitwise OR、
|
運算子)組合。
- re.escape(pattern)¶
對pattern 中的特殊字元進行轉義。如果你想要匹配其中可能包含正規表示式元字元 (metacharacter) 的任意文本字串,這會非常有用。例如:
>>>print(re.escape('https://www.python.org'))https://www\.python\.org>>>legal_chars=string.ascii_lowercase+string.digits+"!#$%&'*+-.^_`|~:">>>print('[%s]+'%re.escape(legal_chars))[abcdefghijklmnopqrstuvwxyz0123456789!\#\$%\&'\*\+\-\.\^_`\|\~:]+>>>operators=['+','-','*','/','**']>>>print('|'.join(map(re.escape,sorted(operators,reverse=True))))/|\-|\+|\*\*|\*
此函式不得用於
sub()
和subn()
中的替換字串,僅應轉義反斜線。例如:>>>digits_re=r'\d+'>>>sample='/usr/sbin/sendmail - 0 errors, 12 warnings'>>>print(re.sub(digits_re,digits_re.replace('\\',r'\\'),sample))/usr/sbin/sendmail - \d+ errors, \d+ warnings
在 3.3 版的變更:
'_'
字元不再被轉義。在 3.7 版的變更:Only characters that can have special meaning in a regular expressionare escaped. As a result,
'!'
,'"'
,'%'
,"'"
,','
,'/'
,':'
,';'
,'<'
,'='
,'>'
,'@'
, and"`"
are no longer escaped.
- re.purge()¶
清除正規表示式快取。
例外¶
- exceptionre.PatternError(msg,pattern=None,pos=None)¶
當傳遞給此處函式之一的字串不是有效的正規表示式(例如它可能包含不匹配的括號)或在編譯或匹配期間發生某些其他錯誤時,將引發例外。如果字串不包含模式匹配項,則絕不是錯誤。
PatternError
實例具有以下附加屬性:- msg¶
未格式化的錯誤訊息。
- pattern¶
正規表示式模式。
- pos¶
pattern 中編譯失敗的索引(可能是
None
)。
- lineno¶
對應pos 的列(可能是
None
)。
- colno¶
對應pos 的欄(可能是
None
)。
在 3.5 版的變更:新增額外屬性。
在 3.13 版的變更:
PatternError
最初被命名為error
;後者為了向後相容性而被保留為別名。
Regular Expression Objects¶
- classre.Pattern¶
Compiled regular expression object returned by
re.compile()
.在 3.9 版的變更:
re.Pattern
supports[]
to indicate a Unicode (str) or bytes pattern.See泛型別名型別.
- Pattern.search(string[,pos[,endpos]])¶
Scan throughstring looking for the first location where this regularexpression produces a match, and return a corresponding
Match
.ReturnNone
if no position in the string matches the pattern; note thatthis is different from finding a zero-length match at some point in the string.The optional second parameterpos gives an index in the string where thesearch is to start; it defaults to
0
. 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 to
endpos-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<re.Match object; span=(0, 1), match='d'>>>>pattern.search("dog",1)# No match; search doesn't include the "d"
- Pattern.match(string[,pos[,endpos]])¶
If zero or more characters at thebeginning ofstring match this regularexpression, return a corresponding
Match
. ReturnNone
if thestring does not match the pattern; note that this is different from azero-length match.The optionalpos andendpos parameters have the same meaning as for the
search()
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".<re.Match object; span=(1, 2), match='o'>
If you want to locate a match anywhere instring, use
search()
instead (see alsosearch() vs. match()).
- Pattern.fullmatch(string[,pos[,endpos]])¶
If the wholestring matches this regular expression, return a corresponding
Match
. ReturnNone
if the string does not match the pattern;note that this is different from a zero-length match.The optionalpos andendpos parameters have the same meaning as for the
search()
method.>>>pattern=re.compile("o[gh]")>>>pattern.fullmatch("dog")# No match as "o" is not at the start of "dog".>>>pattern.fullmatch("ogre")# No match as not the full string matches.>>>pattern.fullmatch("doggie",1,3)# Matches within given limits.<re.Match object; span=(1, 3), match='og'>
在 3.4 版被加入.
- Pattern.findall(string[,pos[,endpos]])¶
Similar to the
findall()
function, using the compiled pattern, butalso accepts optionalpos andendpos parameters that limit the searchregion like forsearch()
.
- Pattern.finditer(string[,pos[,endpos]])¶
Similar to the
finditer()
function, using the compiled pattern, butalso accepts optionalpos andendpos parameters that limit the searchregion like forsearch()
.
- Pattern.flags¶
The regex matching flags. This is a combination of the flags given to
compile()
, any(?...)
inline flags in the pattern, and implicitflags such asUNICODE
if the pattern is a Unicode string.
- Pattern.groups¶
The number of capturing groups in the pattern.
- Pattern.groupindex¶
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.
- Pattern.pattern¶
The pattern string from which the pattern object was compiled.
在 3.7 版的變更:Added support ofcopy.copy()
andcopy.deepcopy()
. Compiledregular expression objects are considered atomic.
Match Objects¶
Match objects always have a boolean value ofTrue
.Sincematch()
andsearch()
returnNone
when there is no match, you can test whether there was a match with a simpleif
statement:
match=re.search(pattern,string)ifmatch:process(match)
- classre.Match¶
Match object returned by successful
match
es andsearch
es.
- Match.expand(template)¶
Return the string obtained by doing backslash substitution on the templatestringtemplate, as done by the
sub()
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. The backreference\g<0>
will bereplaced by the entire match.在 3.5 版的變更:不匹配的群組將被替換為空字串。
- Match.group([group1,...])¶
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, an
IndexError
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, anIndexError
exception 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'
- Match.__getitem__(g)¶
This is identical to
m.group(g)
. This allows easier access toan individual group from a match:>>>m=re.match(r"(\w+) (\w+)","Isaac Newton, physicist")>>>m[0]# The entire match'Isaac Newton'>>>m[1]# The first parenthesized subgroup.'Isaac'>>>m[2]# The second parenthesized subgroup.'Newton'
Named groups are supported as well:
>>>m=re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)","Isaac Newton")>>>m['first_name']'Isaac'>>>m['last_name']'Newton'
在 3.6 版被加入.
- Match.groups(default=None)¶
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 to
None
.舉例來說:
>>>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 to
None
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')
- Match.groupdict(default=None)¶
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 to
None
. For example:>>>m=re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)","Malcolm Reynolds")>>>m.groupdict(){'first_name': 'Malcolm', 'last_name': 'Reynolds'}
- Match.start([group])¶
- Match.end([group])¶
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)
) ism.string[m.start(g):m.end(g)]
Note that
m.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'
- Match.span([group])¶
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.
- Match.pos¶
The value ofpos which was passed to the
search()
ormatch()
method of aregex object. This isthe index into the string at which the RE engine started looking for a match.
- Match.endpos¶
The value ofendpos which was passed to the
search()
ormatch()
method of aregex object. This isthe index into the string beyond which the RE engine will not go.
- Match.lastindex¶
The integer index of the last matched capturing group, or
None
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.
- Match.lastgroup¶
The name of the last matched capturing group, or
None
if the group didn'thave a name, or if no group was matched at all.
- Match.re¶
Theregular expression object whose
match()
orsearch()
method produced this match instance.
在 3.7 版的變更:Added support ofcopy.copy()
andcopy.deepcopy()
. Match objectsare considered atomic.
Regular Expression Examples¶
Checking for a Pair¶
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=re.compile(r".*(.).*\1")>>>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'
模擬 scanf()¶
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.
| Regular Expression |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
search() vs. match()¶
Python offers different primitive operations based on regular expressions:
re.match()
checks for a match only at the beginning of the stringre.search()
checks for a match anywhere in the string(this is what Perl does by default)re.fullmatch()
checks for entire string to be a match
舉例來說:
>>>re.match("c","abcdef")# No match>>>re.search("c","abcdef")# Match<re.Match object; span=(2, 3), match='c'>>>>re.fullmatch("p.*n","python")# Match<re.Match object; span=(0, 6), match='python'>>>>re.fullmatch("r.*n","python")# No match
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<re.Match object; span=(0, 1), match='a'>
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<re.Match object; span=(4, 5), match='X'>
Making a Phonebook¶
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,maxsplit=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,maxsplit=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']]
Text Munging¶
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.'
Finding all Adverbs¶
findall()
matchesall occurrences of a pattern, not just the firstone assearch()
does. For example, if a writer wanted tofind all of the adverbs in some text, they might usefindall()
inthe following manner:
>>>text="He was carefully disguised but captured quickly by police.">>>re.findall(r"\w+ly\b",text)['carefully', 'quickly']
Finding all Adverbs and their Positions¶
If one wants more information about all matches of a pattern than the matchedtext,finditer()
is useful as it providesMatch
objectsinstead of strings. Continuing with the previous example, if a writer wantedto find all of the adverbsand their positions in some text, they would usefinditer()
in the following manner:
>>>text="He was carefully disguised but captured quickly by police.">>>forminre.finditer(r"\w+ly\b",text):...print('%02d-%02d:%s'%(m.start(),m.end(),m.group(0)))07-16: carefully40-47: quickly
Raw String Notation¶
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 ")<re.Match object; span=(0, 4), match=' ff '>>>>re.match("\\W(.)\\1\\W"," ff ")<re.Match object; span=(0, 4), match=' ff '>
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"\\")<re.Match object; span=(0, 1), match='\\'>>>>re.match("\\\\",r"\\")<re.Match object; span=(0, 1), match='\\'>
Writing a Tokenizer¶
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:
fromtypingimportNamedTupleimportreclassToken(NamedTuple):type:strvalue:strline:intcolumn:intdeftokenize(code):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('MISMATCH',r'.'),# Any other character]tok_regex='|'.join('(?P<%s>%s)'%pairforpairintoken_specification)line_num=1line_start=0formoinre.finditer(tok_regex,code):kind=mo.lastgroupvalue=mo.group()column=mo.start()-line_startifkind=='NUMBER':value=float(value)if'.'invalueelseint(value)elifkind=='ID'andvalueinkeywords:kind=valueelifkind=='NEWLINE':line_start=mo.end()line_num+=1continueelifkind=='SKIP':continueelifkind=='MISMATCH':raiseRuntimeError(f'{value!r} unexpected on line{line_num}')yieldToken(kind,value,line_num,column)statements=''' IF quantity THEN total := total + price * quantity; tax := price * 0.05; ENDIF;'''fortokenintokenize(statements):print(token)
The tokenizer produces the following output:
Token(type='IF',value='IF',line=2,column=4)Token(type='ID',value='quantity',line=2,column=7)Token(type='THEN',value='THEN',line=2,column=16)Token(type='ID',value='total',line=3,column=8)Token(type='ASSIGN',value=':=',line=3,column=14)Token(type='ID',value='total',line=3,column=17)Token(type='OP',value='+',line=3,column=23)Token(type='ID',value='price',line=3,column=25)Token(type='OP',value='*',line=3,column=31)Token(type='ID',value='quantity',line=3,column=33)Token(type='END',value=';',line=3,column=41)Token(type='ID',value='tax',line=4,column=8)Token(type='ASSIGN',value=':=',line=4,column=12)Token(type='ID',value='price',line=4,column=15)Token(type='OP',value='*',line=4,column=21)Token(type='NUMBER',value=0.05,line=4,column=23)Token(type='END',value=';',line=4,column=27)Token(type='ENDIF',value='ENDIF',line=5,column=4)Token(type='END',value=';',line=5,column=9)
Friedl, Jeffrey. Mastering Regular Expressions. 3rd ed., O'ReillyMedia, 2009. The third edition of the book no longer covers Python at all,but the first edition covered writing good regular expression patterns ingreat detail.