python 正则表达式

python 正则表达式

blockchain
blockchain

示例1

import re
pattern = '[a-z]*'
print(type(pattern))
print(re.match(pattern,'hello123a').group(0))
#match函数会自动将字符串转换为正则表达式 当后面不符合正则表达式要求时停止匹配。

示例2

import re
pattern1 = re.compile(r'[a-z]*') #匹配任意个小写字母
pattern2 = re.compile(r'[a-z]+ [a-z]+',re.I) #匹配任意个小写字母并且拼上空格在拼上任意个小写字母
print(type(pattern1)) #complie将字符串转换为正则表达式
print(re.match(pattern1,'hello123').group(0))
print(re.match(pattern2,'HeLlo PytHOn').group(0))
#使用compile()函数可以在多次使用正则表达式时不用重复转换,能提高匹配速度。

示例3

import re
str1 = "my name is Jack"
print(re.match(r"my", str1).group(0)) #匹配出字符串my
print(re.match(r"my.{6}", str1).group()) #匹配出字符串my name
print(re.match(r".*", str1).group()) #匹配出所有的字符串,即str1的内容

str2 = "I'm 20 years old"
print(re.match(r"I'm \d", str2).group()) #\d只能匹配一个数字,故结果为:I'm 2
print(re.match(r"I'm \d", str2).group()) #为重复零次或多次,故匹配结果为:I'm 20
print(re.match(r".", str2).group()) #.为匹配任意字符零次或多次,故结果为str2的内容

str4 = "今天天气怎么样?"
print(re.match(r".(天气).", str4).group(1)) #匹配出词语:天气

serach和match只能匹配一次还得用group

findall

import re
str='my 20 years my telephone number is 13169101211'
pattern=re.compile('131\d*')
print(pattern.findall(str))

替换

import re
str1 = "I'm 20 years old#this is a comment"
print(str1)
print(re.sub(r"(\d)+",'30',str1))

group与$

import re
str4 = "今天天气怎么样?"
print(re.match(r'.(天气).(样)',str4).group())
#group 默认值为0,输出匹配的值
##今天天气怎么样

import re
str4 = "今天天气怎么样?"
print(re.match(r'.(天气).(样)',str4).group(1))
#group(1) 输出正则表达式第二个括号里的内容
##样

import re
str4 = "今天天气怎么样?"
print(re.match(r'.(天气).(样)$',str4).group())
#$符号 匹配以什么结尾的 没有以样结尾
#报错

posted @ 2021-11-16 14:25  supermao12  阅读(119)  评论(0)    收藏  举报