python正则表达式简单使用

字符

  • . 所有
  • \ 转义
  • [] 里面的任意

预定义的字符集

  • \d 数字~9
  • \D 取反[^\d]

数量

  • “*” 0~无限
  • “+” 1~无限(找到的数量,不局限于只对找到的第一个找到元素进行操作)
  • {m} m次
  • {m,n} m~次
  • ? 前一个字符0或者1次

常见的用法

Serarch() 找一个
Match() 从头开始找
Fidall() 找全部
Sub() 替换
Compile 编译


import re
from typing import Container 

# re.compile()匹配函数?
# 可以实现更有效率的匹配。https://www.cnblogs.com/python-xiaopang/p/8984034.html

str_1 = '''
asdfecgvserbvADFGEHRA
SF1861ASLKNMLJKasab'''

# compile的用法
# 写法1
# container = re.compile('a(.*)b',re.DOTALL)
# print(container.findall(str_1))
 
# 写法2  S=DOTALL
# print(re.findall(r'a(.*)b',str_1,re.S))

# r的用法 保证原生字符串输出
# str_two = r'c:a\b'
# print(str_two)

# 数字的匹配  注意坑:配合我们的开始和结束
# str_th = '564168519479'
# container = re.compile(r'^\d+$')
# print(container.match(str_th).group())


# 中文的匹配
# str_cn = '阿斯顿发文 对的 hello sdf 大公司'
# container = re.compile('[\u4e00-\u9fa5]+')
# print(container.findall(str_cn))

# 替换
# str_other = 'chuang_ke_xue_yuan'
# container = re.compile('_')
# print(container.sub('',str_other))

# 切割 split
str_sp = '1,a,g.,;;sd,e,f'
container = re.compile('[,;]+')
print(container.split(str_sp))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值