Python小推车动态语言Ruby Python python学习

Python学习打call第二十八天:正则表达式

2019-02-28  本文已影响1人  暖A暖

1.什么是正则表达式(Regular Expression)

2.常用的元字符

. : 匹配任意一个字符,除了换行符号,换行符使用[.\n]模式;

\:转义字符,使后一个字符改变原来的意思;

*:重复匹配0次或更多次;

*?:非贪婪匹配,尽可能少匹配,可能匹配0次;

+:重复匹配1次或更多次;

+?:非贪婪匹配,尽可能少匹配,最少匹配1次;

:重复匹配0次或1次;

^:以...开头;

$:以...结尾;

|:或;

{}:{n}匹配n次,{n,m}匹配n至m次,{n,}匹配至少n次最多无限次;

[]:字符集,对应的位置可以是字符集中任意字符,[abc]表示匹配abc中任意字符,[^abc]表示匹配abc之外的任意字符;

():分组表达式作为一个整体,可以后接数量词,表达式中的|仅在该组中有效;

3.预定义字符集:

4.单次匹配

import re

# match, search, fullmatch是从头开始匹配,match 与 search最大的区别在于:match必须是从开头开始匹配,search可以是从任意位置开始匹配
obj = re.compile('^\w+')
result1 = obj.match('hello  hello')
print(result1)

# 也可以编译和匹配同时进行
result2 = re.match('.*', 'hello')

# re.search( ):搜索匹配一次,返回一个match对象,可以不是从头开始匹配
obj = re.compile('^h?')
result3 = obj.search('hhhhllo hello')
print(result3)

# re.fullmatch( ):匹配整个的字符串或文本,但是同样是从头开始匹配, 必须要完全匹配
obj = re.compile('.*')
result3 = obj.fullmatch('hhhhllo hello')
print(result3)

5.全部匹配

import re

# re.findall(patter, string, flag):匹配多次,返回一个列表,不是从开头查找
obj = re.compile('h\w+o')
result1 = obj.findall('123 你好 hello hello hello')
print(result1)  # 返回列表

obj = re.compile('\w+')
result2 = obj.finditer('hello hello hello')
print(result2) # 返回迭代器

# sub方法是全文替换
import re
s = '''python|hello|xkd|valor|opt|python|python'''
obj = re.compile("p\w+n")
ret = obj.sub("robby",s)
print(ret)

import re
s = '''python|hello|xkd|valor|opt|python|python'''
obj = re.compile("p\w+n")
# sub方法是全文替换
result1 = obj.sub("robby",s)
print(result1)

# 表示只替换一次
result2 = obj.sub("robby",s,1)
print(result2)

# regex.split(s):表示使用regex分割字符串s,返回一个列表
import re
s = '''python|hello|xkd|valor|opt|python|python'''
obj = re.compile("x\w+d")

result3 = obj.split(s)
print(result3)

6.分组

import re
s = """xkd|oc|c++|python|linux|java|swift|ruby"""
obj = re.compile('(x\w+d).*(p\w+n)')

result = obj.search(s)
print(result)

print(result.groups())  # 返回元组
print(result.group(1))  # 返回第一个分组匹配到内容
print(result.group(2))  # 返回第二个分组匹配到内容
print(result.group(0))  # 返回正则表达式匹配到的所有的内容
import re
s = """xkd|oc|c++|python|linux|java|swift|ruby"""

obj = re.compile('(?P<org>x\w+d).*(?P<course>p\w+n)')
result = obj.search(s)
print(result)

print(result.groups())# 返回元组
print(result.groupdict())   # 返回字典

参考:https://www.9xkd.com/user/plan-view.html?id=2259739652

上一篇下一篇

猜你喜欢

热点阅读