.findall() 直接匹配字母和数字
元字符:. ^ $ * + ? {} [] () \
import re print(re.findall("alex","slfdlslalexgsj"))>>>[‘alex‘]
. 表示代表两个任意字符
import re print(re.findall("a..x","slfd123salexgsj"))>>>[‘alex‘]
import reprint(re.findall("a..x","alexsdsadfxdlggsj"))>>>[‘alex‘, ‘adfx‘]
^ 表示从开头开始匹配
import re print(re.findall("^a..x","alexsdsdlggsj")) >>>[‘alex‘]
$ 匹配结尾的位置
import re print(re.findall("a..x$","alexsdsadfxdafhx")) >>>[‘afhx‘]
import re #不能匹配$符print(re.findall("a..x$","alexsdsadfxdafhx$"))>>>[]
* (0,+00) 匹配与前面的一个字符直到无穷次 没有的话匹配为“” 贪婪匹配
1 import re 2 print(re.findall("d*","aldddddddddfhx")) 3 >>>[‘‘, ‘‘, ‘ddddddddd‘, ‘‘, ‘‘, ‘‘, ‘‘]
import reprint(re.findall("^d*","ddddddddhhshfhx"))>>>[‘dddddddd‘]
print(re.findall("alex*","sodale"))>>>[‘ale‘]
+(1,+00) 匹配与前面的一个字符直到无穷次 必须要有一个 贪婪匹配
import reprint(re.findall("alex+","sodalex"))>>>[‘alex‘]
import reprint(re.findall("alex+","sodale"))>>>[]
?(0,1) 最多匹配一个。
import re print(re.findall("alex?","sfhalexxdj"))print(re.findall("alex?","sfhaledj"))>>>[‘alex‘]>>>[‘ale‘]
{0,}==*
{1,}==+
{0,1}==?
{6}==只匹配6个
{1,6}==匹配1~6个
import re print(re.findall("alex{0,3}","sfhalexxdj")) print(re.findall("alex{3}","sfalexxledj")) >>>[‘alexx‘] >>>[]
? 变成惰性匹配
1 import re 2 print(re.findall("alex*?","sfhalexxdj")) 3 print(re.findall("alex+?","sfalexxledj")) 4 >>>[‘ale‘] 5 >>>[‘alex‘]
[] 或的意思 括号里面 都 单独 拿出来匹配 括号内至少要有一个 [a-z]表示a~z
import re print(re.findall("www[oldboy baidu]","wwwbaidu"))print(re.findall("q[a*z]","dfdfduqaa"))print(re.findall("q[a*z]","dfdfduq"))
时间: 2024-10-12 13:28:41