python中re模块二

2022/4/26 14:42:36

本文主要是介绍python中re模块二,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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中re模块二的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程