Python3学习笔记-33(使用正则表达式替换字符串)

 一、正则表达式学习

import re

"""
正则表达式学习
"""

"""
1.匹配单个字符
"""
"""
. 匹配任意一个字符,除了\n
[] 匹配中括号中列举的任意一个字符, 可以不连续
\d 匹配一位数字(0-9)
\D 匹配非数字
\s 匹配空白(空格, tab键等)
\S 匹配非空白
\w 匹配单个字符 a-z A-Z 0-9 _
\W 匹配非单词字符
"""
result_01 = re.match(r"hello[1-8]", "hello8") #第一个参数为正则表达式,第二个参数为要匹配的字符串,如果有返回值,表示匹配正则表达式,反之,不匹配
result_02 = re.match(r"hello[123]", "hello8") #匹配123中任意一个
result_03 = re.match(r"hello[1-36-8]", "hello8") #匹配范围1-3, 6-8
result_04 = re.match(r"hello[1-8a-z]", "helloh") #匹配范围1-8, a-z
result_05 = re.match(r"hello\w", "hello3") #匹配单个字符
result_06 = re.match(r".*", """asd\nasd""", re.S) #参数三 re.S 可以让. 匹配\n
# print(result_06)
print("单个字符匹配", result_06.group())


"""
匹配多个字符
"""
"""
* 匹配前一个字符出现0次或无限次
+ 匹配前一个字符出现1次或无限次
? 匹配前一个字符出现1次或0次
{m} 匹配前一个字符出现m次
{m, n} 匹配前一个字符出现m-n次
"""
ret_01 = re.match(r"hello8{5,10}", "hello888888")
ret_02 = re.match(r"hello\d{5,10}", "hello123456")
# print(ret_01)
print("多个字符匹配", ret_02.group())

"""
^ 匹配字符串开头
$ 匹配字符串结尾
match从头开始匹配
"""

#判断变量名是否合法的正则表达式
"""^[a-zA-Z_][0-9a-zA-Z_]*$"""

"""
匹配分组
"""

"""
| 匹配左右任意一个表达式  会把前面和后面分为两部分,如若要缩小范围,使用'()'  \ 为转义字符
(ab) 将括号中作为一个分组
\num 引用分组num匹配到的字符串,num为分组索引,从1开始
(?Pab) 为分组起别名
(?P=name) 引用别名为name分组匹配到的字符串
"""
rett_01 = re.match(r"[a-z0-9A-Z_]{4,20}@(163|126|qq)\.com", "[email protected]")
print("匹配分组", rett_01.group(1))  #根据分组索引取,默认从1开始    一对小括号为一个分组


"""
search() 不用从头开始匹配,只要有满足的就返回
findall() 以列表的形式返回所有满足正则的字符串,
sub() 三个参数,第一个为正则表达式,第二个为要替换的字符串(也可以是一个函数),第三个为原字符串
split() 根据匹配进行切割字符串,返回一个列表
"""

二、sub的高级基本用法

import re

class Convert():
    s = 'A8C3721D86'

    def convert(self,value):
        matched = value.group()
        if int(matched) >= 6:
            return 'x'
        elif int(matched) < 6:
            return 'k'

c = Convert()
#字符串s中数字大于等于6的替换为x 小于6的替换为k
# r = re.sub('\d', c.convert, Convert.s)
r = re.sub('[0-9]', c.convert, Convert.s)
print(r)

 

你可能感兴趣的:(Python)