正则表达式

re模块

就其本质而言,正则表达式(或 RE)是一种小型的、高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

字符匹配(普通字符,元字符):

1 普通字符:大多数字符和字母都会和自身匹配
              >>> re.findall('alvin','yuanaleSxalexwupeiqi')
                      ['alvin'] 

2 元字符:. ^ $ * + ? { } [ ] | ( ) \

元字符之. ^ $ * + ? { }

 1 import re
 2  
 3 ret=re.findall('a..in','helloalvin')
 4 print(ret)#['alvin']
 5  
 6  
 7 ret=re.findall('^a...n','alvinhelloawwwn')
 8 print(ret)#['alvin']
 9  
10  
11 ret=re.findall('a...n$','alvinhelloawwwn')
12 print(ret)#['awwwn']
13  
14  
15 ret=re.findall('a...n$','alvinhelloawwwn')
16 print(ret)#['awwwn']
17  
18  
19 ret=re.findall('abc*','abcccc')#贪婪匹配[0,+oo]  
20 print(ret)#['abcccc']
21  
22 ret=re.findall('abc+','abccc')#[1,+oo]
23 print(ret)#['abccc']
24  
25 ret=re.findall('abc?','abccc')#[0,1]
26 print(ret)#['abc']
27  
28  
29 ret=re.findall('abc{1,4}','abccc')
30 print(ret)#['abccc'] 贪婪匹配

注意:前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,后面加?号使其变成惰性匹配.

1 ret=re.findall('abc*?','abcccccc')
2 print(ret)#['ab']

元字符之字符集[]:

 1 #--------------------------------------------字符集[]
 2 ret=re.findall('a[bc]d','acd')
 3 print(ret)#['acd']
 4  
 5 ret=re.findall('[a-z]','acd')
 6 print(ret)#['a', 'c', 'd']
 7  
 8 ret=re.findall('[.*+]','a.cd+')
 9 print(ret)#['.', '+']
10  
11 #在字符集里有功能的符号: - ^ \
12  
13 ret=re.findall('[1-9]','45dha3')
14 print(ret)#['4', '5', '3']
15  
16 ret=re.findall('[^ab]','45bdha3')
17 print(ret)#['4', '5', 'd', 'h', '3']
18  
19 ret=re.findall('[\d]','45bdha3')
20 print(ret)#['4', '5', '3']

元字符之转义符\

反斜杠后边跟元字符去除特殊功能,比如\.
反斜杠后边跟普通字符实现特殊功能,比如\d

\d  匹配任何十进制数;它相当于类 [0-9]。
\D 匹配任何非数字字符;它相当于类 [^0-9]。
\s  匹配任何空白字符;它相当于类 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相当于类 [^ \t\n\r\f\v]。
\w 匹配任何字母数字字符;它相当于类 [a-zA-Z0-9_]。
\W 匹配任何非字母数字字符;它相当于类 [^a-zA-Z0-9_]
\b  匹配一个特殊字符边界,比如空格 ,&,#等

 

ret=re.findall('I\b','I am LIST')
print(ret)#[]
ret=re.findall(r'I\b','I am LIST')
print(ret)#['I']

注意:

 1 #-----------------------------eg1:
 2 import re
 3 ret=re.findall('c\l','abc\le')
 4 print(ret)#[]
 5 ret=re.findall('c\\l','abc\le')
 6 print(ret)#[]
 7 ret=re.findall('c\\\\l','abc\le')
 8 print(ret)#['c\\l']
 9 ret=re.findall(r'c\\l','abc\le')
10 print(ret)#['c\\l']
11  
12 #-----------------------------eg2:
13 #之所以选择\b是因为\b在ASCII表中是有意义的
14 m = re.findall('\bblow', 'blow')
15 print(m)
16 m = re.findall(r'\bblow', 'blow')
17 print(m)

元字符之分组():

m = re.findall(r'(ad)+', 'add')
print(m)
 
ret=re.search('(?P<id>\d{2})/(?P<name>\w{3})','23/com')
print(ret.group())#23/com
print(ret.group('id'))#23

元字符之|:

ret=re.search('(ab)|\d','rabhdg8sd')
print(ret.group())#ab

re模块下的常用方法:

 1 import re
 2 #1
 3 re.findall('a','alvin yuan')    #返回所有满足匹配条件的结果,放在列表里
 4 #2
 5 re.search('a','alvin yuan').group()  #函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以
 6                                      # 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
 7  
 8 #3
 9 re.match('a','abc').group()     #同search,不过尽在字符串开始处进行匹配
10  
11 #4
12 ret=re.split('[ab]','abcd')     #先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
13 print(ret)#['', '', 'cd']
14  
15 #5
16 ret=re.sub('\d','abc','alvin5yuan6',1)
17 print(ret)#alvinabcyuan6
18 ret=re.subn('\d','abc','alvin5yuan6')
19 print(ret)#('alvinabcyuanabc', 2)
20  
21 #6
22 obj=re.compile('\d{3}')
23 ret=obj.search('abc123eeee')
24 print(ret.group())#123
import re
ret=re.finditer('\d','ds3sy4784a')
print(ret)        #<callable_iterator object at 0x10195f940>
 
print(next(ret).group())
print(next(ret).group())

注意:

import re
 
ret=re.findall('www.(baidu|oldboy).com','www.oldboy.com')
print(ret)#['oldboy']     这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可
 
ret=re.findall('www.(?:baidu|oldboy).com','www.oldboy.com')
print(ret)#['www.oldboy.com']

 注意:

import re

print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>"))
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>"))
print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>"))
1 #匹配出所有的整数
2 import re
3 
4 #ret=re.findall(r"\d+{0}]","1-2*(60+(-40.35/5)-(-4*3))")
5 ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
6 ret.remove("")
7 
8 print(ret)

1、匹配标签

import re

ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
#还可以在分组中利用?<name>的形式给分组起名字
#获取的匹配结果可以直接用group('名字')拿到对应的值
print(ret.group('tag_name'))  #结果 :h1
print(ret.group())  #结果 :<h1>hello</h1>

ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
#如果不给组起名字,也可以用\序号来找到对应的组,表示要找的内容和前面的组内容一致
#获取的匹配结果可以直接用group(序号)拿到对应的值
print(ret.group(1))
print(ret.group())  #结果 :<h1>hello</h1>

2、匹配整数

import re

ret=re.findall(r"\d+","1-2*(60+(-40.35/5)-(-4*3))")
print(ret) #['1', '2', '60', '40', '35', '5', '4', '3']
ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
print(ret) #['1', '-2', '60', '', '5', '-4', '3']
ret.remove("")
print(ret) #['1', '-2', '60', '5', '-4', '3']

3、小数匹配

re.search("\d+(\.\d+)?", '2.22+3.56+22")  # 后面括号内小数点后的部分,整体可以出现一次或者0次

4、数字匹配

1、 匹配一段文本中的每行的邮箱
      http://blog.csdn.net/make164492212/article/details/51656638

2、 匹配一段文本中的每行的时间字符串,比如:‘1990-07-12’;

   分别取出1年的12个月(^(0?[1-9]|1[0-2])$)、
   一个月的31天:^(30|31|(1|2)[0-9])|0?[1-9]$

    ^([1-2][0-9]{3})-(0?[1-9]|1[0-2])-(30|31|(1|2)[0-9])|0?[1-9]$

3、 匹配qq号。(腾讯QQ号从10000开始)  [1,9][0,9]{4,}

4、 匹配一个浮点数。       ^(-?\d+)(\.\d+)?$   或者  -?\d+\.?\d*

5、 匹配汉字。             ^[\u4e00-\u9fa5]{0,}$ 

6、 匹配出所有整数

计算器

import re


def cal_atom(exp):
    """
    -40/5
    """
    if "/" in exp:
        a, b = exp.split("/")
        return str(float(a)/float(b))
    elif "*" in exp:
        a, b = exp.split("*")
        return str(float(a)*float(b))


def mul_div(exp):
    while True:
        son_exp = re.search("\d+(\.\d+)?[/*]-?\d+(\.\d+)?", exp)  # 匹配括号里面的乘除法,注意乘除号后面的 -?负号可能存在
        if son_exp:
            atom_exp = son_exp.group()
            res = cal_atom(atom_exp)
            exp = exp.replace(atom_exp, res)
        else:
            return exp


def exp_format(exp):
    exp = exp.replace("++", "+")
    exp = exp.replace("+-", "-")
    exp = exp.replace("-+", "-")
    exp = exp.replace("--", "+")
    return exp


def add_sub(exp):
    """
    计算加减法
    """
    ret = re.findall("[+-]?\d+(?:\.\d+)?", exp)
    s = 0
    for i in ret:
        s += float(i)
    return str(s)


@cal_time
def remove_bracket(exp):
    while True:
        ret = re.search("\([^()]+\)", exp)
        if ret:
            no_bracket_exp = ret.group()
            add_sub_exp = mul_div(no_bracket_exp)  # 计算内层括号里面的值,替换回来
            add_sub_exp = exp_format(add_sub_exp)
            res = add_sub(add_sub_exp)
            exp = exp.replace(no_bracket_exp, res)
        else:
            break
    # 所有的括号里面的值算法之后,在按照乘除法,替换符号,加减法的顺序,计算得到最终结果
    exp = mul_div(exp)
    exp = exp_format(exp)
    exp = add_sub(exp)
    return exp


s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
s = s.replace(" ", "")
print(remove_bracket(s))
计算器

在线测试工具 http://tool.chinaz.com/regex/

 https://www.cnblogs.com/Eva-J/articles/7228075.html#_label10

posted @ 2018-07-31 20:51  Mr.GLH  阅读(255)  评论(0)    收藏  举报
Top↑