当前位置: 移动技术网 > IT编程>脚本编程>Python > 正则表达式快速入门

正则表达式快速入门

2019年11月10日  | 移动技术网IT编程  | 我要评论

美女pk精子4,老友记第一季中英文字幕,刘小光二人转mp3

前言

python文档:https://docs.python.org/zh-cn/3/library/re.html?highlight=re#module-re

findall:匹配所有符合条件的内容。

search:匹配第一个符合条件的内容。

sub:替换符合条件的内容

 

1.".":匹配任意字符,换行符"\n"除外

import re

a='yasdfhs'

c=re.findall('y.',a)
print(c)    #输出['ya']

e=re.findall('y..',a)
print(e)   #['yas']

b=re.findall('y...',a)
print(b)   #输出['yasd']

如果被匹配的字符串中有换行符"\n"

import re

b="hello\nworld"
a=re.findall("o.",b)
print(a)    #输出['or']

w="helloworld"
d=re.findall("o.",w)
print(d)    #输出['ow', 'or']

 

2.“*”:匹配前一个字符(0次或无数次)

   "?":匹配前一个字符(1次或0次)

二者的区别就在于下边的例子:

import re

a='hyyssyy'
c=re.findall('s*',a) print(c) #输出 ['', '', '', 'ss', '', '', ''] w=re.findall("s?",a) print(w) #输出 ['', '', '', 's', 's', '', '', ''] # 如果在字符和字符串之间加空格 c=re.findall('s *',a) print(c) #输出 ['s', 's'] w=re.findall("s ?",a) print(w) #输出['s', 's'] #很显然,"*"和"?"都不会匹配空格代表的内容

 

3.".*":贪心算法(尽可能匹配多的符合条件的内容)

 “.*?”:非贪心算法(尽可能匹配较少的符合条件的内容)

 "()":把括号内的数据作为结果输出

二者的区别就在于下边的例子:

import re 

a_cod="xxxixxxxxxlikexxxxxxpythonxxx"

g=re.findall('xxx.*xxx',a_cod)
print(g)    #输出['xxxixxxxxxlikexxxxxxpythonxxx']

s=re.findall('xxx(.*)xxx',a_cod)
print(s)    #输出['ixxxxxxlikexxxxxxpython']

d=re.findall('xxx.*?xxx',a_cod)
print(d)    #输出['xxxixxx', 'xxxlikexxx', 'xxxpythonxxx']

h=re.findall('xxx(.*?)xxx',a_cod)
print(h)    #输出['i', 'like', 'python']

#加入小括号"()"的作用一目了然,目的是为了使其只显示符合条件的目标的内容,增加美观度。

 

4.“s”:使条件语句能够匹配空格,换行等等

import re

a_cod='''xhelloxx
pythonxx!x'''

d=re.findall('x(.*?)x',a_cod)
print(d)    #输出['hello', '']

a=re.findall('x(.*?)x',a_cod,re.s)
print(a)    #输出['hello', '\npython', '!']

 

5.对比'findall'和'search'函数

import re

a_cod='''xhelloxx
pythonxx!x'''

a=re.search('x(.*?)x',a_cod,re.s)
print(a)    #输出<re.match object; span=(0, 7), match='xhellox'>

#"search"中只匹配了“hello”

q=re.findall('x(.*?)x',a_cod,re.s)
print(q)    #输出['hello', '\npython', '!']

 

6.“sub”:替代

import re

a='1xxx1'

s=re.sub('1(.*?)1','456',a)
print(s)    #输出456

d=re.sub('1(.*?)1','1%s1','asddf')
print(d)    #输出asddf

 

以上就是正则表达式快速入门的几个常用方法,学会以上方法的就可以尝试制作简单的爬虫

如有不足,欢迎大家指出!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网