量化金融基础篇 [ python 正则表达 ]

创建正则表达对象:

import re
find_item = re.compile('正则表达字符串')
find_result = find_item.search('指定索要搜索的字符串')
find_result.group() #返回搜索之后的结果

可以通过括号进行正则匹配进行分组:

find_item = re.compile(r'(匹配1)(匹配2)')
find_result = find_item.search('string')
#接着通过group(group_index)
find_result.group(0) #匹配1结果
find_result.group(1) #匹配2结果

通过管道符号 | 来做“或”的匹配

find_item = re.compile(r'匹配1 | 匹配2')
find_result = find_item.search('string')

通过?来做可选的匹配

find_item = re.compile(r'字符串(可选匹配字符串)?字符串')
find_result = find_item.search('字符串')

通过*号来做匹配0次或者多次的操作

find_item = re.compile(r'字符串(多次匹配的字符串)*字符串')
find_result = find_item.search('字符串')

通过+号来做匹配1次或者多次的操作

find_item = re.compile(r'字符串(匹配)+字符串')
find_result = find_item.search('字符串')

通过{}号来做特定次数的匹配操作

#做1~3次的匹配
find_item = re.compile(r'字符串(匹配){1,3}字符串')
find_result = find_item.search('字符串')

需要注意的是,花括号的匹配结果是最长匹配结果,即匹配重复出现最长的字符串为贪心的匹配模式,如果想要以最短的方式进行匹配,需要在{}后面加一个?号

#非贪心匹配模式
find_item = re.compile(r'字符串(匹配){1,3}?字符串')
find_result = find_item.search('字符串')

其他{}用法:

{n}匹配n次,{n,}匹配n次或者更多,{,m}匹配0次~m次,{n,m}匹配n~m次


findall()方法,search()方法只返回一个match的对象,而findall()则返回所有被匹配的结果,存入在一个list当中

字符串分类:

\d 任意数字,\w任意字母数字下划线字符,\s空格、制表符或者换行

将他们进行大写则表示除了这种类型以外的字符


建立自己制定的匹配集合:

#只匹配aB45这四个字符
find_item = re.compile(r'[aB45]')
#自创集合取反操作,除了aB45字符以外都会匹配
find_item = re.compile(r'[^aB45]')

从头开始匹配,表示开头必须有这个字符串才会匹配

find_item = re.compile(r'^字符串')

结尾皮牌,表示结尾必须有这个字符串才会匹配

find_item = re.compile(r'字符串$')

统配符 .

#任意字符匹配一次
find_item = re.compile(r'字符串.字符串')

#任意字符匹配任意次
find_item = re.compile(r'字符串.*字符串')

compile()方法还接受第二个参数,可以指定一些比较特殊的匹配方式

#到第一个换行符为止,找到想要的结果
find_item = re.compile(r'匹配',re.DOTALL)

#不分大小写的匹配
find_item = re.compile(r'匹配',re.I)

匹配到对应的文字并进行替换的方法:sub()

find_item = re.compile(r'匹配')
find_item.sub('替换文字','要替换的字符串')

复杂的匹配方式可以通过```符号将匹配模式写成多行的方式:

find_item = re.compile(
  '''(
     匹配1
     匹配2
     匹配3
  )''',re.VERBOSE #忽略正则表达中的空白符和注释
)

多个控制模式的传入方式:

find_item = re.compile(r'匹配',re.I | re.DOTALL | re.VERBOSE)





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值