Python常用正则表达式符号浅析

WBOY
Release: 2016-06-06 11:32:11
Original
1155 people have browsed it

对Python中正则表达式的理解,主要就是对符号的理解,本文即对Python中常用的正则表达式符号进行简析。其主要的符号有:

.
默认匹配一个字符,不包含换行符,如果设置DOTALL则匹配换行符

^
匹配行首

$
匹配行尾

*
匹配0个或者多个重复


匹配一个或者多个重复


匹配一个或者零个重复

*?,+?,??
按照非贪婪模式匹配

{m},{m,n},{m,n}?
分别匹配m个重复,m至n个重复,m至n个重复按照非贪婪模式

\
转义

[]
[abc],[a-z][^a-z]
|
或者匹配 'a|b'
(...)
匹配组

(?iLmsux)

(&#63;:...) (&#63;P<name>...)
>>> re.match('(&#63;P<name>abc){2}','abcabc').groupdict()
{'name': 'abc'}
(&#63;P=name)
>>> re.match(r'(&#63;P<name>abc)----(&#63;P=name)','abc----abc').group()
'abc----abc'
(&#63;#...) #后面的内容为注释
(&#63;=...)

Copy after login

匹配的字符串后面的内容需要匹配

>>> re.match(r'phone(&#63;=\d{3})','phone123').group()
'phone'#

(&#63;!...)

Copy after login

匹配的字符后面内容不能匹配

>>> re.match(r'phone(&#63;!\d{3})','phoneabc123').group()
'phone'
(&#63;<=...)
Copy after login

匹配的字符串前面需要匹配

(?

(?(id/name)yes-pattern|no-pattern)
\number
\A 匹配字符串的开头
\b 匹配单词边界

\B
\b的反义

\d 表示[0-9]
\D表示 [^0-9]
\s表示 [ \t\r\n\f\v]
\S 为非空白字符
\w等价于 [a-zA-Z0-9]
\W \w的反义

\Z 匹配字符串的结束

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template