python小马哥的Python专题

Python进阶1 - 正则表达式: 使用正则表达式

2019-05-21  本文已影响140人  小马哥China

做好一件事情不难,只要敢于迈出第一步,然后不断迈出下一步就行了.小马哥也会把每一个专题文章从最简单的内容开始发布,每天不断迭代修改,添加内容.用最简单的方式积累和传递有用的东西.


本文重点: 介绍Python针对正则表达式的常用函数

import re

#(1)使用match()方法匹配字符串

# match()在字符串的起始部分进行匹配: 如果匹配成功,返回一个匹配对象;如果匹配失败,返回一个None

# group()方法能够用于显示成功的匹配

result = re.match(pattern ='hello',string ='hello python')    # 返回一个re.Match对象

if result is not None:

    print(result.group())#返回成功的匹配

#match特点: 在字符串的起始位置开始匹配,即使字符串比模式长也会match成功,

#(2)使用search()方法在字符串中查找

# 不是所有的字符串都是在开头部分进行匹配,更多的情况是搜索字符串中是否包含指定的模式/模板

# search方法与match方法的不同在于,match是在字符串的开头进行匹配,而search可以搜索字符串的任意位置,只有遇到一次匹配就返回匹配对象,否则返回None

#search()方法会自左到右一次匹配字符串,直到第一次出现的位置

m = re.match('python','hello python')

if m is not None:print('Match(): ',m.group())

s = re.search('python','hello python')

if s is not None:print('Search(): ',s.group())

#(3)匹配对个模式: 择一匹配符号的使用

patterns ='Mark|Jack|Pony'

result = re.match(patterns,'Pony Ma')

if result is not None:

    print(result.group())

result = re.search(patterns,'Alibaba,Jack Ma')

if result is not None:

    print(result.group())

#(4)匹配任何单个字符

#注意不能匹配换行符或者非字符(空字符串)

msg ='hello go'

pattern ='g.'

result = re.search(pattern,msg)

if result is not None:

    print(result)

    print(result.group())

msg2 ='hello \nyou'

pattern ='.you'

result = re.search(pattern,msg2)

if result is None:

    print(result)

#注意: 如果想匹配标点:".",要通过使用转移符号\来解决

msg3 ='nlgc@163.com'

pattern ='\.com'  #如果一定要匹配一个".",那么要加上\,否则,就会任意符合条件的字符串都会被匹配到

result = re.search(pattern,msg3)

if result is not None:

    print(result.group())

#(5)创建字符集

pattern ='[abcd]'

msg ='x'

result = re.match(pattern,msg)

print(type(result))

#(6)特殊字符( ., \d, \w, \s)与分组以及频数(+, *, ?)的使用

#匹配电子邮件xxxxx@yyyyy.com

pattern ='\w+@(.)*?.com'

email ='mark123@yeah.163.com'

result = re.match(pattern,email)

print(type(result))

#(7)匹配字符串的起始和结尾以及单词边界

#一般这种位置用于search()中,在字符串中搜索出符合模式的字符串,因为match()就是在字符串的起始位置开始的

msg ='Lost years are worse than lost dollars.'

pattern ='^Lost(.*)$'

result = re.match(pattern,msg)

if result is not None:

    print(result.groups())

#(8)使用findall()查找每一次出现的位置

#findall(): 查询字符串中某个正则表达式模式全部匹配情况,结果包含在列表里面返回

msg ='hello1 python,hello2 java,hello3 go'

pattern ='hello\d'

result = re.findall(pattern,msg)

print(result)

#(9)使用finditer()更加节省内存

#(10)使用sub()和subn()替换字符串中符合模式的子字符串

#subn()和sub()功能一样,但是多了一个返回被替换的个数

#将welcome变量里面的name换做name变量里面的字符串Mark

name ='Mark'

welcome ='Good morning,name!'

result = re.sub('name',name,welcome)

print(result)

result_plus = re.subn('name',name,welcome)

print(result_plus)#同sub()一样会返回替换完成之后的句子,但是作为元组,还会返回被修改的模式的次数

#(11)split()分割字符串

data ='邮政编码:100000'

pattern =':'

result = re.split(pattern,data)

print(result)

上一篇 下一篇

猜你喜欢

热点阅读