python基础-正则

 https://www.runoob.com/python/python-reg-expressions.html

 

python 正则表达式匹配中,(.*)和(.*?)匹配区别?

#@正则表达式匹配中,(.*)和(.*?)匹配区别?
#(.*)是贪婪匹配,会把满足正则的尽可能多的往后匹配
#(.*?)是非贪婪匹配,会把满足正则的尽可能少匹配
import re
s= str("<a>哈哈</a><a>啦啦</a>")
res1 = re.findall("<a>(.*)</a>",s)
print(res1)
res2 = re.findall("<a>(.*?)</a>",s)
print(res2)

输出结果:

['哈哈</a><a>啦啦']
['哈哈', '啦啦']

 

import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
    print("matchObj.group() : ", matchObj.group())
    print("matchObj.group(1) : ", matchObj.group(1))
    print("matchObj.group(2) : ", matchObj.group(2))
else:
    print("No match!!")
  •  (.*) 第一个匹配分组,.* 代表匹配除换行符之外的所有字符。
  •  (.*?) 第二个匹配分组,.*? 后面多个问号,代表非贪婪模式,也就是说只匹配符合条件的最少字符
  •  后面的一个 .* 没有括号包围,所以不是分组,匹配效果和第一个一样,但是不计入匹配结果中。

输出:

matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter

 

校验邮箱格式代码

import re
text = input("Please input your Email address:\n")
if re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$',text):
  print('Email address is Right!')
else:
  print('Please reset your right Email address!')

 

匹配一行文字中的所有开头的字母内容

s="i love you not because of who you are, but because of who i am when i am with you"
content = re.findall(r"\b\w",s)
print(content)

输出:
['i', 'l', 'y', 'n', 'b', 'o', 'w', 'y', 'a', 'b', 'b', 'o', 'w', 'i', 'a', 'w', 'i', 'a', 'w', 'y']

\b 匹配一个单词边界,也就是指单词和空格间的位置。例如, 'er\b' 可以匹配"never" 中的 'er',但不能匹配 "verb" 中的 'er'。
\w 匹配字母数字及下划线

 

匹配一行文字中的所有开头的数字内容

s="i love you not because 12sd 34er 56df e4 54434"

content=re.findall(r"\b\d",s)

 

只匹配包含字母和数字的行

s="i love you not because\n12sd 34er 56\ndf e4 54434"
content=re.findall(r"\w+",s,re.M)
print(content)
输出结果:
['i', 'love', 'you', 'not', 'because', '12sd', '34er', '56', 'df', 'e4', '54434']

 

posted @ 2021-04-09 15:31  milkty  阅读(140)  评论(0)    收藏  举报