ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python 中的re 常用命令

2022-08-17 18:00:34  阅读:144  来源: 互联网

标签:python mo compile re phoneNumRegex 常用命令 print mo1


import re

phoneNumRegex = re.compile(r'zhang(wei|yang|hao)')
mo = phoneNumRegex.search('my number zhangwei,zhangyang')
print(mo.groups())

# ?前面字符是可选择的
batRegex = re.compile(r'Bat(wo)?man')
mo1 = batRegex.search('The ADventures of Batwoman')
print(mo1.group())

# *前面字符匹配零次或者多次
batRegx = re.compile(r'Bat(wo)*man')
mo1 = batRegx.search('The Adventures of Batwowowowoman')
print(mo1.group())

# +匹配一次或者多次(必须至少出现一次)
batRegx = re.compile(r'Bat(wo)+man')
mo1 = batRegx.search('The Adventures of Batwowoman')
print(mo1.group())

# {}配置特定次数
batRegx = re.compile(r'(ha){2,3}')
mo1 = batRegx.search('hahahahaha')
print(mo1.group())

# 只会匹配一个415-555-9999
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('cell:415-555-9999 work:211-555-0000')
print(mo.group())

# findall匹配字符串中的所有  返回一个列表
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.findall('cell:415-555-9999 work:211-555-0000')
print(mo)
# 如果有分组 返回一个元组列表
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
mo = phoneNumRegex.findall('cell:415-555-9999 work:211-555-0000')
print(mo)


#字符分类
\d           0-9的任意数字
\D           除0-9的数字以外的任意字符
\w           任意字母,数字,下划线字符
\W           除字母数字下划线以外的任意字符
\s           空格制表符或者换行符
\S           除空格制表符换行符以外的任何字符

phoneNumRegex = re.compile(r'\d+\s+\w+')
mo = phoneNumRegex.findall('122 pigs,23 hello,999    world,888hello')
print(mo)


# .通配符 除了换行以外的所有字符 只匹配后面一个字符
phoneNumRegex = re.compile(r'ra.')
mo = phoneNumRegex.findall('rahh,rwooh')
print(mo)
#['rah']


# 用.* 匹配所有字符
phoneNumRegex = re.compile(r'first name:(.*)last name:(.*)')
mo = phoneNumRegex.findall('first name:zhang last name:wei')
print(mo)

#不区分大小写匹配
phoneNumRegex = re.compile(r'you|me',re.I)
mo = phoneNumRegex.findall('You 200 ME 900')
print(mo)


用sub 方法替换字符串
phoneNumRegex = re.compile(r'wangmeng \s\w+')
mo = phoneNumRegex.sub('zhangwei','wangmeng money 20')
print(mo)

 

标签:python,mo,compile,re,phoneNumRegex,常用命令,print,mo1
来源: https://www.cnblogs.com/zhangweimee/p/16596193.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有