Regular Expressions Flashcards

1
Q

. (Dot.)

A

.
(Dot.) In the default mode, this matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Caret.

A

(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

$

A

$
Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in ‘foo1\nfoo2\n’ matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in ‘foo\n’ will find two (empty) matches: one just before the newline, and one at the end of the string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

*

A

*
Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’ followed by any number of ‘b’s.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

+

A

+
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 not match just ‘a’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

?

A

?

Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either ‘a’ or ‘ab’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

*?, +?, ??

A

?, +?, ??
The ‘
’, ‘+’, and ‘?’ qualifiers are all greedy; they match as much text as possible. Sometimes this behaviour isn’t desired; if the RE is matched against ‘<a> b ‘, it will match the entire string, and not just ‘</a><a>’. Adding ? after the qualifier makes it perform the match in non-greedy or minimal fashion; as few characters as possible will be matched. Using the RE will match only ‘</a><a>’.</a>

</a>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

{m}

A

{m}
Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six ‘a’ characters, but not five.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

{m,n}

A

{m,n}
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 ‘a’ characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match ‘aaaab’ or a thousand ‘a’ characters followed by a ‘b’, but not ‘aaab’. The comma may not be omitted or the modifier would be confused with the previously described form.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

{m,n}?

A

{m,n}?
Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string ‘aaaaaa’, a{3,5} will match 5 ‘a’ characters, while a{3,5}? will only match 3 characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

\

A

\
Either escapes special characters (permitting you to match characters like ‘*’, ‘?’, and so forth), or signals a special sequence; special sequences are discussed below.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

[]

A

[]
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 separating them by a ‘-‘, for example [a-z] will match any lowercase ASCII letter, [0-5][0-9] will match all the two-digits numbers from 00 to 59, 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 lose their special meaning inside sets. For example, [(+)] will match any of the literal characters ‘(‘, ‘+’, ‘’, or ‘)’.

Character classes such as \w or \S (defined below) are also accepted inside a set, although the characters they match depends on whether ASCII or LOCALE mode is in force.

Characters that are not within a range can be matched by complementing the set. If the first character of the set is ‘^’, all the characters that are not in the set will be matched. For example, [^5] will match any character except ‘5’, and [^^] will match any character except ‘^’. ^ has no special meaning if it’s not the first character in the set.

To match a literal ‘]’ inside a set, precede it with a backslash, or place it at the beginning of the set. For example, both [()[]{}] and [{}] will both match a parenthesis.

Support of nested sets and set operations as in Unicode Technical Standard #18 might be added in the future. This would change the syntax, so to facilitate this change a FutureWarning will be raised in ambiguous cases for the time being. That includes sets starting with a literal ‘[’ or containing literal character sequences ‘–’, ‘&&’, ‘~~’, and ‘||’. To avoid a warning escape them with a backslash.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

A|B

A

A|B, where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the ‘|’ in this way. This can be used inside groups (see below) as well. As the target string is scanned, REs separated by ‘|’ are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the ‘|’ operator is never greedy. To match a literal ‘|’, use |, or enclose it inside a character class, as in [|].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

(…)

A

(…)
Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has 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: [(], [)].

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

(?…)

A

(?…)
This is an extension notation (a ‘?’ following a ‘(‘ is not meaningful otherwise). The first character after the ‘?’ determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; (?P…) is the only exception to this rule. Following are the currently supported extensions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

(?aiLmsux)

A

(?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: 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), and re.X (verbose), for the entire regular expression. (The flags are described in Module Contents.) This is useful if you wish to include the flags as part of the regular expression, instead of passing a flag argument to the re.compile() function. Flags should be used first in the expression string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

(?:…)

A

(?:…)
A non-capturing version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group cannot be retrieved after performing a match or referenced later in the pattern.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

(?aiLmsux-imsx:…)

A

(?aiLmsux-imsx:…)
(Zero or more letters from the set ‘a’, ‘i’, ‘L’, ‘m’, ‘s’, ‘u’, ‘x’, optionally followed by ‘-‘ followed by one or more letters from the ‘i’, ‘m’, ‘s’, ‘x’.) The letters set or remove 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), re.U (Unicode matching), and re.X (verbose), for the part of the expression. (The flags are described in Module Contents.)

The letters ‘a’, ‘L’ and ‘u’ are mutually exclusive when used as inline flags, so they can’t be combined or follow ‘-‘. Instead, when one of them appears in an inline group, it overrides the matching mode in the enclosing group. In Unicode patterns (?a:…) switches to ASCII-only matching, and (?u:…) switches to Unicode matching (default). In byte pattern (?L:…) switches to locale depending matching, and (?a:…) switches to ASCII-only matching (default). This override is only in effect for the narrow inline group, and the original matching mode is restored outside of the group.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

(?P…)

A

(?P…)
Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named.

Named groups can be referenced in three contexts. If the pattern is (?P[’”]).*?(?P=quote) (i.e. matching a string quoted with either single 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 object m

m. group(‘quote’)
m. end(‘quote’) (etc.)

in a string passed to the repl argument of re.sub()

\g

\g<1>

\1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

(?P=name)

A

(?P=name)

A backreference to a named group; it matches whatever text was matched by the earlier group named name.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

(?#…)

A

(?#…)

A comment; the contents of the parentheses are simply ignored.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

(?=…)

A

(?=…)
Matches if … matches next, but doesn’t consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match ‘Isaac ‘ only if it’s followed by ‘Asimov’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

(?!…)

A

(?!…)
Matches if … doesn’t match next. This is a negative lookahead assertion. For example, Isaac (?!Asimov) will match ‘Isaac ‘ only if it’s not followed by ‘Asimov’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

(?<=…)

A

(?<=…)
Matches if the current position in the string is preceded by a match for … that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in ‘abcdef’, since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not. Note that patterns which start with positive lookbehind assertions will not match at the beginning of the string being searched; you will most likely want to use the search() function rather than the match() function:

>>>
import re
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’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

(?

A

(?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

(?(id/name)yes-pattern|no-pattern)

A

(?(id/name)yes-pattern|no-pattern)
Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn’t. no-pattern is optional and can be omitted. For example, (|$) is a poor email matching pattern, which will match with ‘’ as well as ‘user@host.com’, but not with ‘’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

\number

A

\number
Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches ‘the the’ or ‘55 55’, but not ‘thethe’ (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the ‘[’ and ‘]’ of a character class, all numeric escapes are treated as characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

\A

A

\A

Matches only at the start of the string.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

\b

A

\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 boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r’\bfoo\b’ matches ‘foo’, ‘foo.’, ‘(foo)’, ‘bar foo baz’ but not ‘foobar’ or ‘foo3’.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

\B

A

\B
Matches the empty string, but only when it is not at the beginning or end of a word. This means that r’py\B’ matches ‘python’, ‘py3’, ‘py2’, but not ‘py’, ‘py.’, or ‘py!’. \B is just the opposite of \b, so word characters in Unicode patterns are Unicode alphanumerics or the underscore, although this can be changed by using the ASCII flag. Word boundaries are determined by the current locale if the LOCALE flag is used.

31
Q

\d

A
\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. If the ASCII flag is used only [0-9] is matched.

For 8-bit (bytes) patterns:
Matches any decimal digit; this is equivalent to [0-9].

32
Q

\D

A

\D
Matches any character which is not a decimal digit. This is the opposite of \d. If the ASCII flag is used this becomes the equivalent of [^0-9].

33
Q

\s

A

\s
For Unicode (str) patterns:
Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.
For 8-bit (bytes) patterns:
Matches characters considered whitespace in the ASCII character set; this is equivalent to [ \t\n\r\f\v].

34
Q

\S

A

\S
Matches any character which is not a whitespace character. This is the opposite of \s. If the ASCII flag is used this becomes the equivalent of [^ \t\n\r\f\v].

35
Q

\w

A
\w
For Unicode (str) patterns:
Matches Unicode word characters; this includes most characters that can be part of a word in any language, as well as numbers and the underscore. If the ASCII flag is used, only [a-zA-Z0-9_] is matched.

For 8-bit (bytes) patterns:
Matches characters considered alphanumeric in the ASCII character set; this is equivalent to [a-zA-Z0-9_]. If the LOCALE flag is used, matches characters considered alphanumeric in the current locale and the underscore.

36
Q

\W

A

\W
Matches any character which is not a word character. This is the opposite of \w. If the ASCII flag is used this becomes the equivalent of [^a-zA-Z0-9_]. If the LOCALE flag is used, matches characters which are neither alphanumeric in the current locale nor the underscore.

37
Q

\Z

A

\Z

Matches only at the end of the string.

38
Q

re.compile(pattern, flags=0)

A

re.compile(pattern, flags=0)
Compile a regular expression pattern into a regular expression object, which can be used for matching using its match(), search() and other methods, described below.

The expression’s behaviour can be modified by specifying a flags 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 using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

39
Q

re. A

re. ASCII

A

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 only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).

Note that for backward compatibility, the re.U flag still exists (as well as its synonym re.UNICODE and its embedded counterpart (?u)), but these are redundant in Python 3 since matches are Unicode by default for strings (and Unicode matching isn’t allowed for bytes).

40
Q

re.DEBUG

A

re.DEBUG

Display debug information about compiled expression. No corresponding inline flag.

41
Q

re. I

re. IGNORECASE

A

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 the re.ASCII flag is used to disable non-ASCII matches. The current locale does not change the effect of this flag unless the re.LOCALE flag is also used. Corresponds to the inline flag (?i).

Note that when the Unicode patterns [a-z] or [A-Z] are used in combination with the IGNORECASE flag, they will match the 52 ASCII letters and 4 additional non-ASCII letters: ‘İ’ (U+0130, Latin capital letter 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 the ASCII flag is used, only letters ‘a’ to ‘z’ and ‘A’ to ‘Z’ are matched.

42
Q

re. L

re. LOCALE

A

re.L
re.LOCALE
Make \w, \W, \b, \B and case-insensitive matching dependent on the current locale. This flag can be used only with bytes patterns. The use of this flag is discouraged as the locale mechanism is very unreliable, it only handles one “culture” at a time, and it only works with 8-bit locales. Unicode matching is already enabled by default in Python 3 for Unicode (str) patterns, and it is able to handle different locales/languages. Corresponds to the inline flag (?L).

Changed in version 3.6: re.LOCALE can be used only with bytes patterns and is not compatible with re.ASCII.

43
Q

re. M

re. MULTILINE

A

re.M
re.MULTILINE
When specified, the pattern character ‘^’ matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character ‘$’ matches at the end of the string and at the end of each line (immediately preceding each newline). By default, ‘^’ matches only at the beginning of the string, and ‘$’ only at the end of the string and immediately before the newline (if any) at the end of the string. Corresponds to the inline flag (?m).

44
Q

re. S

re. DOTALL

A

re.S
re.DOTALL
Make the ‘.’ special character match any character at all, including a newline; without this flag, ‘.’ will match anything except a newline. Corresponds to the inline flag (?s).

45
Q

re. X

re. VERBOSE

A

re.X
re.VERBOSE
This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pattern is ignored, except when in a character class, or when preceded by an unescaped backslash, or within tokens like *?, (?: or (?P. When a line contains a # that is not in a character class and is not preceded 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 a decimal 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).

46
Q

re.search(pattern, string, flags=0)

A

re.search(pattern, string, flags=0)
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

47
Q

re.match(pattern, string, flags=0)

A

re.match(pattern, string, flags=0)
If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

Note that even in MULTILINE mode, re.match() will only match at the beginning of the string and not at the beginning of each line.

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

48
Q

re.fullmatch(pattern, string, flags=0)

A

re.fullmatch(pattern, string, flags=0)
If the whole string matches the regular expression pattern, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

New in version 3.4.

49
Q

re.split(pattern, string, maxsplit=0, flags=0)

A

re.split(pattern, string, maxsplit=0, flags=0)
Split string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.

> > > 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.’, 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 of the string, the result will start with an empty string. The same holds for the end of the string:

> > > re.split(r’(\W+)’, ‘…words, words…’)
[’’, ‘…’, ‘words’, ‘, ‘, ‘words’, ‘…’, ‘’]
That way, separator components are always found at the same relative indices within the result list.

Empty matches for the pattern split the string only when not adjacent to a previous 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’, ‘…’, ‘’, ‘’, ‘’]

50
Q

re.findall(pattern, string, flags=0)

A

re.findall(pattern, string, flags=0)
Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

51
Q

re.finditer(pattern, string, flags=0)

A

re.finditer(pattern, string, flags=0)
Return an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.

52
Q

re.sub(pattern, repl, string, count=0, flags=0)

A

re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \& are left alone. Backreferences, such as \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{‘
If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example:

> > > def dashrepl(matchobj):
… if matchobj.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 a pattern object.

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous empty match, so sub(‘x*’, ‘-‘, ‘abxd’) returns ‘-a-b–d-‘.

In string-type repl arguments, in addition to the character escapes and backreferences described above, \g will use the substring matched by the group named name, as defined by the (?P…) syntax. \g uses the corresponding group number; \g<2> is therefore equivalent to \2, but isn’t ambiguous in a replacement such as \g<2>0. \20 would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character ‘0’. The backreference \g<0> substitutes in the entire substring matched by the RE.

53
Q

re.subn(pattern, repl, string, count=0, flags=0)

A

re.subn(pattern, repl, string, count=0, flags=0)

Perform the same operation as sub(), but return a tuple (new_string, number_of_subs_made).

54
Q

re.escape(pattern)

A

re.escape(pattern)
Escape special characters in pattern. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. For example:

> > > print(re.escape(‘http://www.python.org’))
http://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))))
/|-|+|**|*
This function must not be used for the replacement string in sub() and subn(), only backslashes should be escaped. For example:

> > > 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

55
Q

re.purge()

A

re.purge()

Clear the regular expression cache.

56
Q

exception re.error(msg, pattern=None, pos=None)

A

exception re.error(msg, pattern=None, pos=None)
Exception raised when a string passed to one of the functions here is not a valid regular expression (for example, it might contain unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern. The error instance has the following additional attributes:

msg
The unformatted error message.

pattern
The regular expression pattern.

pos
The index in pattern where compilation failed (may be None).

lineno
The line corresponding to pos (may be None).

colno
The column corresponding to pos (may be None).

57
Q

Pattern.search(string[, pos[, endpos]])

A

Pattern.search(string[, pos[, endpos]])
Scan through string looking for the first location where this regular expression produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the ‘^’ pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.

The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match. If endpos is less than pos, no match will be found; otherwise, if rx is a compiled regular expression object, rx.search(string, 0, 50) is equivalent to rx.search(string[:50], 0).

> > > pattern = re.compile(“d”)
pattern.search(“dog”) # Match at index 0

> > > pattern.search(“dog”, 1) # No match; search doesn’t include the “d”

58
Q

Pattern.match(string[, pos[, endpos]])

A

Pattern.match(string[, pos[, endpos]])
If zero or more characters at the beginning of string match this regular expression, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos 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”.

If you want to locate a match anywhere in string, use search() instead (see also search() vs. match()).

59
Q

Pattern.fullmatch(string[, pos[, endpos]])

A

Pattern.fullmatch(string[, pos[, endpos]])
If the whole string matches this regular expression, return a corresponding match object. Return None if the string does not match the pattern; note that this is different from a zero-length match.

The optional pos and endpos 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.

60
Q

Match.expand(template)

A

Match.expand(template)
Return the string obtained by doing backslash substitution on the template string template, 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) are replaced by the contents of the corresponding group.

61
Q

Match.group([group1, …])

A

Match.group([group1, …])
Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return 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 a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. 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…) syntax, the groupN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an IndexError exception is raised.

A moderately complicated example:

> > > m = re.match(r”(?P\w+) (?P\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’

62
Q

Match.__getitem__(g)

A

Match.__getitem__(g)
This is identical to m.group(g). This allows easier access to an 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’

63
Q

Match.groups(default=None)

A

Match.groups(default=None)
Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.

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 groups might participate in the match. These groups will default to None unless the default 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’)

64
Q

Match.groupdict(default=None)

A

Match.groupdict(default=None)
Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to None. For example:

> > > m = re.match(r”(?P\w+) (?P\w+)”, “Malcolm Reynolds”)
m.groupdict()
{‘first_name’: ‘Malcolm’, ‘last_name’: ‘Reynolds’}

65
Q

Match.groupdict(default=None)

A

Match.groupdict(default=None)
Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name. The default argument is used for groups that did not participate in the match; it defaults to None. For example:

> > > m = re.match(r”(?P\w+) (?P\w+)”, “Malcolm Reynolds”)
m.groupdict()
{‘first_name’: ‘Malcolm’, ‘last_name’: ‘Reynolds’}

66
Q

Match.start([group])

Match.end([group])

A

Match.start([group])
Match.end([group])
Return the indices of the start and end of the substring matched by group; group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match. For a match object m, and a group g that did contribute to the match, the substring matched by group g (equivalent to m.group(g)) is

m.string[m.start(g):m.end(g)]
Note that m.start(group) will equal m.end(group) if group matched a null string. For example, after m = re.search(‘b(c?)’, ‘cba’), m.start(0) is 1, m.end(0) is 2, m.start(1) and m.end(1) are both 2, and m.start(2) raises an IndexError exception.

An example that will remove remove_this from email addresses:

>>>
>>> email = "tony@tiremove_thisger.net"
>>> m = re.search("remove_this", email)
>>> email[:m.start()] + email[m.end():]
'tony@tiger.net'
67
Q

Match.span([group])

A

Match.span([group])
For a match m, return the 2-tuple (m.start(group), m.end(group)). Note that if group did not contribute to the match, this is (-1, -1). group defaults to zero, the entire match.

68
Q

Match.pos

A

Match.pos
The value of pos which was passed to the search() or match() method of a regex object. This is the index into the string at which the RE engine started looking for a match.

69
Q

Match.endpos

A

Match.endpos
The value of endpos which was passed to the search() or match() method of a regex object. This is the index into the string beyond which the RE engine will not go.

70
Q

Match.lastindex

A

Match.lastindex
The integer index of the last matched capturing group, or None if no group was matched at all. For example, the expressions (a)b, ((a)(b)), and ((ab)) will have lastindex == 1 if applied to the string ‘ab’, while the expression (a)(b) will have lastindex == 2, if applied to the same string.

71
Q

Match.lastgroup

A

Match.lastgroup
The name of the last matched capturing group, or None if the group didn’t have a name, or if no group was matched at all.

72
Q

Match.re

A

Match.re

The regular expression object whose match() or search() method produced this match instance.

73
Q

Match.string

A

Match.string

The string passed to match() or search().