要匹配的模式和字符串可以是Unicode字符串以及8位字符串。
\\。
通常在Python代码中,模式的表示使用这种原始字符串符号。
这些函数是快捷的方式,它们不要求你首先编译一个正则表达式对象,但会遗漏一些调优的参数。
请参见
- Mastering Regular Expressions 《精通正则表达式》
- 该书第 2 版不再涵盖Python内容,但其第 1 版中涵盖了很多写得不错、非常详细的正则表达式模式。
1.1 正则表达式语法
此模块中的函数让你检查一个特定的字符串是否匹配给定的正则表达式(或给定的正则表达式是否匹配特定的字符串,这可归结为同一件事)。
关于理论的细节及正则表达式的实现,请参阅上文引用的Friedl的书或任何一本有关编译器构造的教科书。
进一步的信息和更友好的演示,请参阅正则表达式HOWTO。
引号'。)
'\x00'。
特殊字符有:
- '.'
- DOTALL 标志被指定, 则匹配包括换行符在内的所有字符.
- '^'
- MULTILINE模式下也匹配换行符之后的位置.
- '$'
- 一个是换行符之前,一个是字符串的末尾。
- '*'
- ab*将匹配‘a’、‘ab’或‘a’ 后面跟随任意数目的‘b’。
- '+'
- ab+将匹配‘a’之后跟随任意多个数目不为零的‘b’,它将不能匹配单纯的一个‘a’。
- '?'
- ab?将匹配‘a’或者‘ab’。
- *?, +?, ??
- '<H1>'。
- {m}
- 'a'字符,5个将不能匹配。
- {m,n}
- 逗号不可以省略,否则该修改符将与前面的形式混淆。
- {m,n}?
- a{3,5}?将只匹配3个字符。
- '\'
-
特殊序列在下面讨论。
这比较复杂和难以理解,因此强烈建议你为所有即使是最简单的表达式使用原始字符串。
- []
-
在一个集合中:
- 'k'。
- '-'。
- ')'。
- \S(在下文定义),尽管它们匹配的字符取决于LOCALE或UNICODE模式是否是强制的。
- ^如果不是集合中的第一个字符则没有特殊的含义。
- []()[{}]都将匹配一个圆括号。
- '|'
- [|].
- (...)
- [)]。
- (?...)
- Following are the currently supported extensions.
- (?iLmsux)
-
re.compile()函数。
如果在这个标志之前有非空白字符,结果是未定义的。
- (?:...)
- 匹配括号中的任何正则表达式,但是匹配的子字符串不能在匹配后提取或在模式中引用。
- (?P<name>...)
-
海员象征性的组织也是带编号的组,就好像组未被命名。
(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
m - m.group('quote')
- m.end('quote') (etc.)
re.sub() - \g<quote>
- \g<1>
- \1
- (?P=name)
- 它将匹配之前被关联到name中的所有内容。
- (?#...)
- 圆括号内容可简单忽略。
- (?=...)
- 'Asimov'.
- (?!...)
- 'Asimov'.
- (?<=...)
-
match ()函数:
>>> import re >>> m = re.search('(?<=abc)def', 'abcdef') >>> m.group(0) 'def'本示例查看后面一个连字符的词:
>>> m = re.search('(?<=-)\w+', 'spam-egg') >>> m.group(0) 'egg' - (?<!...)
- Patterns which start with negative lookbehind assertions may match at the beginning of the string being searched.
- (?(id/name)yes-pattern|no-pattern)
-
'<user@host.com'.
在 2.4 版本新。
- \number
- ']' of a character class, all numeric escapes are treated as characters.
- \A
- Matches only at the start of the string.
- \b
- represents the backspace character, for compatibility with Python’s string literals.
- \B
- UNICODE.
- \d
- UNICODE, it will match whatever is classified as a decimal digit in the Unicode character properties database.
- \D
- UNICODE, it will match anything other than character marked as digits in the Unicode character properties database.
- \s
- \t\n\r\f\v] plus whatever is classified as space in the Unicode character properties database.
- \S
- UNICODE is set, then any character not marked as space in the Unicode character properties database is matched.
- \w
- [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database.
- \W
- [0-9_] plus characters classied as not alphanumeric in the Unicode character properties database.
- \Z
- 只在字符串的结尾处进行匹配
UNICODE的生效。
由正则表达式分析器也接受大多数支持通过 Python 字符串的标准转义:
\a \b \f \n
\r \t \v \x
\\
字符串文本总是八进制转义顶多是三个数字的长度。
1.2. Module Contents
大多数非平凡应用程序总是使用的已编译的形式。
- compile(pattern, flags=0)
-
search ()方法,如下所述。
|运算符)。
序列
prog = re.compile(pattern) result = prog.match(string)等效于
result = re.match(pattern, string)re.compile()和保存所产生的正则表达式对象重用效率更高时该表达式会在单个程序中多次使用。
注
re.compile()的最新模式的已编译的版本进行缓存,所以只有几个正则表达式的程序使用一次不必担心编译正则表达式。
- DEBUG
-
显示调试信息编译的表达式。
- I
- IGNORECASE
-
这不被受当前的区域设置。
- L
- LOCALE
-
\S dependent on the current locale.
- M
- MULTILINE
-
'$'只匹配字符串的末尾和字符串末尾换行符(如果有的话)之前的位置。
- S
- DOTALL
-
'.'将匹配任何内容除换行符。
- U
- UNICODE
-
\S 取决于UNICODE定义的字符属性.
在 2.0 版中的新。
- X
- VERBOSE
-
'#'通过行末尾将被忽略。
这意味着两个以下正则表达式匹配的对象,一个十进制数是相同的功能:
a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X) b = re.compile(r"\d+\.\d*")
- search(pattern, string, flags=0)
-
请注意这不同于在字符串的某个位置中找到一个长度为零的匹配。
- match(pattern, string, flags=0)
请注意这是不同于零长度匹配。
re.match()将只匹配字符串的开头,而不是在每个行的开头。
search () (请参见search () 与 match ())。
re.fullmatch(pattern, string, flags=0)
-
如果整个字符串匹配正则表达式模式,则返回一个match对象。如果字符串与模式不匹配,则返回None;请注意:这与长度为0的match是有区别的。
新版本3.4
- split(pattern, string, maxsplit=0, flags=0)
-
这已被固定在以后的版本。)
>>> 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']同样对于字符串的末尾:
>>> re.split('(\W+)', '...words, words...') ['', '...', 'words', ', ', 'words', '...', '']这样一来,分离器组件始终都位于相同的相对索引在结果列表中 (例如,如果有是在分离器,在 0,第二个捕获组等等)。
举个例子:
>>> re.split('x*', 'foo') ['foo'] >>> re.split("(?m)^$", "foo\n\nbar\n") ['foo\n\nbar\n']添加可选的标志参数。
- findall(pattern, string, flags=0)
-
空匹配包含在结果中,除非他们接触到另一场匹配的开头。
在 1.5.2 版本新。
添加可选的标志参数。
- finditer(pattern, string, flags=0)
-
空匹配包含在结果中,除非他们接触的另一个匹配的开头。
新版本 2.2 中的。
添加可选的标志参数。
- sub(pattern, repl, string, count=0, flags=0)
-
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{'举个例子:
>>> 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'模式可以是一个字符串或重新对象。
'-a-b-c-'。
\g<0> substitutes in the entire substring matched by the RE.
添加可选的标志参数。
- subn(pattern, repl, string, count=0, flags=0)
-
number_of_subs_made)。
添加可选的标志参数。
- escape(string)
-
这是有用的如果你想匹配一个任意的文本字符串,在它可能包含正则表达式元字符。
- purge()
-
清除正则表达式缓存。
- error
-
如果一个字符串包含不匹配的一种模式,它永远不会是一个错误。
1.3. Regular Expression Objects
- class re.RegexObject
-
编译的正则表达式对象支持以下方法和属性:
- ])
-
请注意这是不同于找到一个长度为零的匹配在一些点在字符串中。
' ^'模式字符匹配在真正开始的字符串和位置刚换行,但不是一定是在开始搜索的索引。
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"
- ])
请注意这是不同于零长度匹配。
search ()方法。
>>> 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 ...>search() (请参见search() 与 match())。
- fullmatch(string[, pos[, endpos]])
-
如果整个字符串匹配正则表达式模式,则返回一个match对象。如果字符串与模式不匹配,则返回None;请注意:这与长度为0的match是有区别的。
新版本3.4
>>> 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. <_sre.SRE_Match object; span=(1, 3), match='og'>
- split(string, maxsplit=0)
-
split ()函数相同。
- ])
-
match()。
- ])
-
match()。
- sub(repl, string, count=0)
-
sub()函数完全相同。
- subn(repl, string, count=0)
-
subn()函数完全相同。
- flags
-
(吗?...)模式中的内联标志。
- groups
-
捕获模式中的组数。
- groupindex
-
这本词典是空的如果在模式中使用了无符号的组。
- pattern
-
模式字符串中从中重新对象的编译。
1.4. Match Objects
- class re.MatchObject
-
if 的语句:
match = re.search(pattern, string) if match: process(match)Match 对象支持下列方法和属性:
- expand(template)
-
\g<name>) are replaced by the contents of the corresponding group.
- ])
-
如果一组包含在模式匹配多次的一部分,则返回最后一场比赛。
>>> 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')IndexError异常。
一个适度复杂的例子:
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") >>> m.group('first_name') 'Malcolm' >>> m.group('last_name') 'Reynolds'通过它们的索引还可以获取到已命名的组:
>>> m.group(1) 'Malcolm' >>> m.group(2) 'Reynolds'如果一组匹配多次,只有最后一个匹配可访问:
>>> m = re.match(r"(..)+", "a1b2c3") # Matches 3 times. >>> m.group(1) # Returns only the last match. 'c3'
- ])
-
在以后的版本 (从 1.5.1 对),单身人士返回元组在这种情况下)。
举个例子:
>>> m = re.match(r"(\d+)\.(\d+)", "24.1632") >>> m.groups() ('24', '1632')无,除非给出了默认参数:
>>> 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')
- ])
-
举个例子:
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds") >>> m.groupdict() {'first_name': 'Malcolm', 'last_name': 'Reynolds'}
- ])
- ])
-
m.group(g)) 匹配的子字符串是
m.string[m.start(g):m.end(g)]IndexError异常。
将删除的电子邮件地址remove_this的示例:
>>> email = "tony@tiremove_thisger.net" >>> m = re.search("remove_this", email) >>> email[:m.start()] + email[m.end():] 'tony@tiger.net'
- ])
-
组的默认值为零,整场比赛。
- pos
-
这是重新引擎开始寻找匹配的字符串中的索引。
- endpos
-
这是之外,重新引擎不会将字符串中的索引。
- lastindex
-
2,如果应用到相同的字符串。
- lastgroup
-
没有如果小组不是有一个名称,或者如果没有组均在所有匹配。
- re
-
作法实例的正则表达式对象。
- string
-
search ()传递的字符串。
1.5. Examples
1.5.1. 检查对子
在这个例子中,我们将使用下面的 helper 函数去更优雅地显示 match 对象:
def displaymatch(match):
if match is None:
return None
return '<Match: %r, groups=%r>' % (match.group(), match.groups())
若想查看给定字符串是否为一手有效牌的话,可履行以下操作:
>>> 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=()>"
若想以正则表达式匹配它的话,可使用如下反向引用:
>>> 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',)>"
作法() 方法:
>>> 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>", line 1, in <module>
re.match(r".*(.).*\1", "718ak").group(1)
AttributeError: 'NoneType' object has no attribute 'group'
>>> pair.match("354aa").group(1)
'a'
1.5.2. 模拟 scanf() 函数
scanf()格式标记和正则表达式之间的等价映射。
| 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]+ |
若想从下述字符串提取文件名和数字
/usr/sbin/sendmail - 0 errors, 4 warnings
scanf() 格式
%s - %d errors, %d warnings
等价的正则表达式为
(\S+) - (\d+) errors, (\d+) warnings
1.5.3. search() vs. match()
re.search()检查是否在任何地方 (这是默认情况下,Perl 做的) 的字符串匹配。
举个例子:
>>> re.match("c", "abcdef") # No match
>>> re.search("c", "abcdef") # Match
<_sre.SRE_Match object at ...>
search ()来限制进行匹配字符串的开头(“^”表示匹配字符串的开头):
>>> re.match("c", "abcdef") # No match
>>> re.search("^c", "abcdef") # No match
>>> re.search("^a", "abcdef") # Match
<_sre.SRE_Match object at ...>
' ^'将匹配每行开头。
>>> re.match('X', 'A\nB\nX', re.MULTILINE) # No match
>>> re.search('^X', 'A\nB\nX', re.MULTILINE) # Match
<_sre.SRE_Match object at ...>
1.5.4. 制作一个电话本
该方法是将文本数据转换为数据结构,可以轻松地阅读和修改由 Python 作为显示在下面的示例创建一个电话簿非常宝贵。
通常它可能来自一个文件,在这里我们使用的三重引号的字符串语法:
>>> 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"""
现在我们转换字符串到一个列表中的每个非空的行,有它自己的条目:
>>> 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']
split () :
>>> [re.split(":? ", entry, 3) for entry in 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']]
maxsplit ,我们可以分开的街道名称门牌号码:
>>> [re.split(":? ", entry, 4) for entry in 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']]
1.5.5. Text Munging
>>> def repl(m):
... inner_word = list(m.group(2))
... random.shuffle(inner_word)
... return m.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.'
1.5.6. 查找所有副词
findall()以下列方式:
>>> text = "He was carefully disguised but captured quickly by police."
>>> re.findall(r"\w+ly", text)
['carefully', 'quickly']
1.5.7. 查找所有副词和它们的位置
finditer()方式如下:
>>> text = "He was carefully disguised but captured quickly by police."
>>> for m in re.finditer(r"\w+ly", text):
... print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))
07-16: carefully
40-47: quickly
1.5.8. Raw 字符串表示法
For example, the two following lines of code are functionally identical:
>>> re.match(r"\W(.)\1\W", " ff ")
<_sre.SRE_Match object at ...>
>>> re.match("\\W(.)\\1\\W", " ff ")
<_sre.SRE_Match object at ...>
, making the following lines of code functionally identical:
>>> re.match(r"\\", r"\\")
<_sre.SRE_Match object at ...>
>>> re.match("\\\\", r"\\")
<_sre.SRE_Match object at ...>