Python正则表达式

正则表达式:

#正则表达式:1、正则表达式的作用:匹配字符串(字符串提供的方法是完全匹配)
#引入正则表达式的目的是模糊匹配
s='hello world'
print(s.find('ll')) #查找第一个字符出现的索引
ret=s.replace('ll','xx')
print(ret)
print(s.split(' ')) #一个列表以空格分割

import re
ret=re.findall('ww{2}l','hello world')
print(ret)
ret=re.findall('alex','ndbvijsialexgr') #完全匹配
print(ret)
#特殊功能的元字符:
# . 除了换行符,代指所有的字符,一个.只能代指一个字符
ret=re.findall('w..l','hello world')
print(ret)
# ^ 通配符,只以最开始的位置匹配 $只在最后位置匹配
ret=re.findall('^h...o','hujoohello world')
print(ret)
ret=re.findall('a..x$','dinualex')
print(ret)
# * 重复匹配,0到多次(贪婪匹配)
ret=re.findall('a.*ll','alexlihelloworld') #重复*前面的字符0到多次
print(ret)
ret=re.findall('ab*','fdiabbubuyb')
print(ret)
# + 重复匹配,1到多次
ret=re.findall('a+b','caaaabhg')
print(ret)
# ? 0或1次(惰性匹配)
ret=re.findall('a?b','caaaabbhg') #0个a或1个a
print(ret)
# {} 自定义匹配多少次
ret=re.findall('a{5}b','caaaaabbhg') #0个a或1个a
print(ret)
ret=re.findall('a{1,3}b','caaaaabbhg') #0个a或1个a
print(ret)
#结论:*等于{0,正无穷} +等于{1,正无穷} ?等于{0,1}
#{1,}等价于{1,正无穷}
# 字符集 []
================================================================================
import re
# 字符集 [] 或 取消元字符的特殊功能( ^ - 例外)
ret=re.findall('a[cde]x','acxadx')
print(ret)
ret=re.findall('[a-z]','acx')
print(ret)
ret=re.findall('[*,.]','abc*.')
print(ret)
ret=re.findall('[1-9,a-zA-Z]','jrininngn') #匹配所有
print(ret)
# ^ 在[]表示取反
ret=re.findall('[^t,b]','ngb,ttpd')
print(ret)
# 反斜杠后边跟元字符去除特殊功能,反斜杠后边跟普通字符实现特殊功能

# d 匹配任何十进制数,它相当于类[0-9]
# D 匹配任何非数字字符,它相当于类[^0-9]
# s 匹配任何空白字符,它相当于类[ fv]
# S 匹配任何非空白字符,它相当于类[^ fv]
# w 匹配任何字母数字字符,它相当于类[a-zA-Z0-9]
# W 匹配任何非字母数字字符,它相当于类[^a-zA-Z0-9]
#  匹配一个特殊字符边界,也就是指单词和空格间的位置

print(re.findall('d{11}','b181838464848491848484848'))
print(re.findall('sabc','tytt abc'))
print(re.findall('wabc','cfchjbkabc'))
print(re.findall('w','cfc abc'))
print(re.findall(r'I','I am a LI$ST'))
print(re.findall(r'S','I am a LI$ST'))
#只匹配第一个满足条件的内容
ret=re.search('sb','ndfvsbdvsb')
print(ret) #<_sre.SRE_Match object; span=(4, 6), match='sb'>
print(ret.group()) #取出search出的值
ret=re.search('a','agbdb').group()
print(ret)
# \ 两个表示一个
ret=re.findall(r'\','abbjvno')
print(ret)
ret=re.search('blow','blow')
print(ret)
#() 分组 |(或两边的内容)
print(re.search('(as)+','njdasnj').group())
print(re.search('(as)|k','njdask6j').group())
#=====================================================
import re
#命名分组
ret=re.search('(?P<id>d{3})/(?P<name>w{3})','weeew134ttt123/oooo')
print(ret.group())
print(ret.group('id'))
print(ret.group('name'))
#=============================================================
#正则表达式的方法
#findall() :所有的结果都返回发哦一个列表里
#search() :返回匹配到的第一个对象(object),对象可以调用group()返回结果
#match() :只在字符串开始匹配。也返回匹配到的第一个对象(object),对象可以调用group()返回结果
ret=re.match('asd','asdjnvvasdj')
print(ret.group())
#split() :
ret=re.split('[j,s]','jlsdjksal')
print(ret)
#sub() :替换
ret=re.sub('a..x','s..b','gfibalexnjnfj')
print(ret)
#compile() :多次使用可以方便
ret=re.findall('.com','hdfhb.comfvb')
print(ret)
obj=re.compile('.com')
ret=obj.findall('hdfhb.comfvb.combh')
print(ret)

import re
ret=re.search('([^()]+)','(1+(2+5)*2)')
print(ret.group()) #(2+5)

#计算器功能

import re
#检测是否有空格
def check_expression(string):
    check_result=True
    if not string.count("(")==string.count(")"):
        print("表达式错误,括号未闭合")
        check_result = False
    if re.findall('[a-z]',string.lower()):
        print('表达式错误,包含非法字符')
        check_result=False

    return check_result
#格式化处理
def format_string(string):
    string = string.replace(' ','')
    string = string.replace('++', '+')
    string = string.replace('--', '+')
    string = string.replace('+-', '-')
    string = string.replace('-+', '-')
    string = string.replace('*+', '*')
    string = string.replace('/+', '/')
    return string

def calc_mul_div(string):
    regular='d+.?d* [*/] [-]?d+.?d*'
    while re.findall(regular,string):
        expression=re.search(regular,string).group()
        if expression.count('*'):
            x,y=expression.split('*')
            mul_result=str(float(x)*float(y))
            string=string.replace(expression,mul_result)
            string=format_string(string)
        if expression.count('/'):
            x,y=expression.split('/')
            div_result=str(float(x)/float(y))
            string=string.replace(expression,div_result)
            string=format_string(string)
    return string

def calc_add_sub(string):
    #ret1 = re.search('d+.?d* [+-] d+.?d*', s).group()
    add_regular='[-]?d+.?d*+[-]?d+.?d*'
    sub_regular='[-]?d+.?d*-[-]?d+.?d*'
    while re.findall(add_regular,string):
        add_list=re.findall(add_regular,string)
        for add_str in add_list:
            x,y=add_str.split('+')
            add_result='+'+str(float(x)+float(y))
            string=string.replace(add_str,add_result)
        string=format_string(string)
    while re.findall(sub_regular,string):
        sub_list=re.findall(sub_regular,string)
        for sub_str in sub_list:
            numbers=sub_str.split('-')
            if len(numbers)==3:
                result=0
                for v in numbers:
                    if v:
                        result-=float(v)
            else:
                x,y=numbers
                result=float(x)-float(y)
            string=string.replace(sub_str,'+'+str(result))
        string=format_string(string)
    return string

source='1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
if check_expression(source):
    print('source:',source)
    print('eval result:',eval(source))
    source=format(source)
    print(source)

    while source.count("(")>0:
        strs = re.search('([^()]*)', source).group()
        replace_str = calc_mul_div(strs)
        replace_str = calc_add_sub(replace_str)  # (17)'strs[1,-1]'
        source = format_string(source.replace(strs, replace_str[1:-1]))
    else:
        replace_str = calc_mul_div(source)
        replace_str = calc_add_sub(replace_str)
        source=source.replace(source,replace_str)
    print('my result:',source.replace('+',''))

#source: 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
# eval result: 2776672.6952380957
# 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
# my result: 2776672.6952380957

  

原文地址:https://www.cnblogs.com/cxli99/p/8463187.html