1.python正则表达式中匹配(match)和查找(search)的区别
答:正则表达式中match和search的方法比较相似
相同点:都是在一个字符串s中寻找pat子字符串,如果能找到,就返回一个Match对象,如果找不到,就返回None。
不同点:mtach方法是从头开始匹配,而search方法,可以在s字符串的任一位置查找。
从结果中,我们可以看出,
python中用match和search方法都可以反馈ours中的our字符串,而对于flourish,只有search能返回Match对象,而因为不是在头部匹配到,所以match方法返回了None。
2.再python中group和groups的区别
答:group和groups是两个不同的函数。
一般,m.group(N) 返回第N组括号匹配的字符。
而m.group()== m.group(0) ==所有匹配的字符,与括号无关,这个是API规定的。
m.groups() 返回所有括号匹配的字符,以tuple格式(元组格式),不包括
m.group(0),即整个表达式.
m.groups()== (m.group(0), m.group(1),……)
3.python中运用正则去除以下html文件中的标签,只显示文本信息。
答:利用python正则表达式re模块中的sub方法,将标签替换为空字符串,代码如下
#-*- cording:utf-8 -*-
importre#去除标签
s= "
小当家
\python面试题汇总
\"p= r"?\w+>|nbsp;"print(re.sub(p," ",s))#打印
小当家
python面试题汇总
4.python中用正则表达式提取字符串中所有域名:
答:利用sub方法,将整个字符串替换为只含域名的字符串。代码如下:
#-*- coding:utf-8 -*-
importre#提取出域名
s2 = """http://www.baidu.com/?id=35
http://youku.com/news_show.asp?id=14
http://taobao.com?id=768
http://toutiao.com/?newsid=377&id=6
http://www.jd.com/newslist.asp?id=415"""p= r"(http://.+?/).+"
print(re.sub(p,lambda x :x.group(1),s2))#打印
http://www.baidu.com/http://youku.com/http://taobao.com?id=768http://toutiao.com/http://www.jd.com/
5.利用python正则表达式,从字符串"hello world luozhixiang"中,提取出所有单词
答:利用split方法分割空格或者用findall方法寻找到所有的单词,代码如下
#-*- coding:utf-8 *-
importre
s= 'hello world china'p= re.split(r"+",s)
res= re.findall(r"\b\w+\b",s)print(p)print(res)#打印
['hello', 'world', 'china']
['hello', 'world', 'china']
6.python正则表达式中“.*”和“.*?”的区别
表达式 .*的意思很好理解,就是单个字符匹配任意次,即贪婪匹配。
表达式 .*? 是满足条件的情况只匹配一次,即懒惰匹配
演示代码和演示结果如下:
#-*- coding :utf-8 -*-
importre
p_1= re.compile(".*([1-9]\\d*|[一两二三四五六七八九十]{1,3})(百|千|)米.*")
p_2= re.compile(".*?([1-9]\\d*|[一两二三四五六七八九十]{1,3})(百|千|)米.*")
string= "附近5100米"all_data_1=p_1.findall(string)
all_data_2=p_2.findall(string)for data inall_data_1:print(data)for data inall_data_2:print(data)#打印
('100', '')
('5100', '')
7.利用python语言,使用正则将字符串"罗志祥202004月真的很倒霉,替蒋凡当了3695489点伤害"中,连续5个以上数字替换成*
#-*- coding:utf-8-*-
importre
s="罗志祥202004月真的很倒霉,替蒋凡当了3695489点伤害"res= re.compile(r'\d{5}')
ret= res.sub('*',s)print(ret)#打印
罗志祥*4月真的很倒霉,替蒋凡当了*89点伤害