2019/02/08
正则表达式
Regular Expression
掌握特殊符号
* (0, +00) # 贪婪匹配,按最多的匹配
>>> re.findall(‘alex*‘, ‘sddgljalexdhgb‘)
[‘alex‘]
>>> re.findall(‘alex*‘, ‘sdghshalexxxxxgdhg‘)
[‘alexxxxx‘]
+ (1, +00) # 贪婪匹配,按最多的匹配
>>> re.findall(‘alex+‘, ‘sdghshalexxxxxgfhg‘)
[‘alexxxxx‘]
? (0, 1) # 匹配前面的字母0个或1个
re.findall(‘alex?‘, ‘sdfaleghhfg‘)
[‘ale‘]
>>> re.findall(‘alex?‘, ‘dsalexxxdggh‘)
[‘alex‘]
{} {0, } == *
{1, } == +
{0, 1} == ?
{6} # 重复6次
{1,6} # 重复1——6任意次
>>> re.findall(‘alex{1,6}‘, ‘sgalexxxxxxxxxxgdfgfdgdxx‘)
[‘alexxxxxx‘]
>>> re.findall(‘alex{1,6}‘, ‘sgalexxgdfgfdgdxx‘)
[‘alexx‘]
^ # 开头直接匹配
>>> re.findall(‘^alex‘, ‘agfhjghfhd‘)
[]
>>> re.findall(‘^alex‘, ‘alexjghfhd‘)
[‘alex‘]
. # 通配符
>>> re.findall(‘alex.‘, ‘alexxc‘)
[‘alexx‘]
>>> re.findall(‘ale....x‘, ‘sdfaledfdfxfxx‘)
[‘aledfdfx‘]
>>> re.findall(‘q[a-z]‘, ‘fgjqfd‘)
[‘qf‘]
>>> re.findall(‘q[a-z]*‘, ‘fgjqfd6g‘)
[‘qfd‘]
>>> re.findall(‘q[a*z]‘, ‘sfqaaasdsdz‘)
[‘qa‘]
>>> re.findall(‘q[0-9]*‘, ‘sfsdqfgkg88‘)
[‘q‘]
>>> re.findall(‘q[A-Z]*‘, ‘sdfgqgsdgq‘)
[‘q‘, ‘q‘]
>>> re.findall(‘q[^a-z]‘, ‘sdfdsqwre‘) # ^ 代表非
[]
>>> re.findall(‘q[^a-z]‘, ‘sdfdsq77re‘)
[‘q7‘]
计算器作业,先找出最里层括号
>>> re.findall("\([^()]*\)", "12 + ( 34 * 6 + 2 - 5 * (2 - 1))")
[‘(2 - 1)‘]
\ # 最重要的转义字符,有意义-->无意义,无意义--->有意义
\d # 匹配任何十进制数,相当于类[0-9]
\D # 匹配任何非数字字符,相当于类[^0-9]
>>> re.findall("\d", "12 + ( 34 * 6 + 2 - 5 * (2 - 1))")
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘6‘, ‘2‘, ‘5‘, ‘2‘, ‘1‘]
>>> re.findall("\d+", "12 + ( 34 * 6 + 2 - 5 * (2 - 1))")
[‘12‘, ‘34‘, ‘6‘, ‘2‘, ‘5‘, ‘2‘, ‘1‘]
>>> re.findall("[0-9]+", "12 + ( 34 * 6 + 2 - 5 * (2 - 1))")
[‘12‘, ‘34‘, ‘6‘, ‘2‘, ‘5‘, ‘2‘, ‘1‘]
>>> re.findall("\D", "12+(34*6+2-5*(2-1))")
[‘+‘, ‘(‘, ‘*‘, ‘+‘, ‘-‘, ‘*‘, ‘(‘, ‘-‘, ‘)‘, ‘)‘]
>>>
\s # 匹配任何空白字符,相当于类[\t\n\r\f\v]
\S # 匹配任何非空白字符,相当于类[^\t\n\r\f\v]
>>> re.findall("\s", "hello world!")
[‘ ‘]
>>> re.findall("\S", "hello world!")
[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘, ‘!‘]
>>> re.findall("\S+", "hello world!")
[‘hello‘, ‘world!‘]
>>>
\w # 匹配任何字母数字字符和_,相当于类[a-zA-Z0-9_]
>>> re.findall("\w", "hello _world!")
[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘_‘, ‘w‘, ‘o‘, ‘r‘, ‘l‘, ‘d‘]
>>> re.findall("\w+", "hello _world!")
[‘hello‘, ‘_world‘]
>>>
\W # 匹配任何非字母数字字符,相当于类[^a-zA-Z0-9_]
>>> re.findall("\W+", "hello _world!")
[‘ ‘, ‘!‘]
>>>
\ # \ 转义
>>> re.findall(‘www*baidu‘, ‘www*baidu‘)
[]
>>> re.findall(‘www\*baidu‘, ‘www*baidu‘)
[‘www*baidu‘]
>>>
原文地址:https://www.cnblogs.com/qianjunye/p/10356603.html
时间: 2024-10-10 19:17:05