一、re模块

re模块中常用的方法。
- match: 默认从字符串开头开始匹配,re.match('fun', 'funny') 可以匹配出来 'fun'
match(pattern, string, flags=0):
"""Try to apply the pattern at the start of the string, returning
a match object, or None if no match was found."""
return _compile(pattern, flags).match(string)

  • search: 扫描整个字符串,返回匹配到的第一个结果,否则返回None,re.search('f\d*', 'sdf23kf2') 匹配到 'f23'

    search(pattern, string, flags=0):

    """Scan through string looking for a match to the pattern, returning

    a match object, or None if no match was found."""

    return _compile(pattern, flags).search(string)

  • findall: 匹配字符串中所有符合pattern的字符,并返回一个列表

    findall(pattern, string, flags=0):

    """Return a list of all non-overlapping matches in the string.

    If one or more capturing groups are present in the pattern, return

    a list of groups; this will be a list of tuples if the pattern

    has more than one group.

    Empty matches are included in the result."""

    return _compile(pattern, flags).findall(string)

  • sub: 第一个参数pattern,第二个replace替换字符,第三个string,第四个count,表示替换几次。同str.replace(repl, string, count)一样

    sub(pattern, repl, string, count=0, flags=0):

    """Return the string obtained by replacing the leftmost

    non-overlapping occurrences of the pattern in string by the

    replacement repl. repl can be either a string or a callable;

    if a string, backslash escapes in it are processed. If it is

    a callable, it's passed the match object and must return

    a replacement string to be used."""

    return _compile(pattern, flags).sub(repl, string, count)

  • split: 按照匹配字符分割字符串。re.split('a', '1a2a3a4') --> [1, 2, 3, 4]

    split(pattern, string, maxsplit=0, flags=0):

    """Split the source string by the occurrences of the pattern,

    returning a list containing the resulting substrings. If

    capturing parentheses are used in pattern, then the text of all

    groups in the pattern are also returned as part of the resulting

    list. If maxsplit is nonzero, at most maxsplit splits occur,

    and the remainder of the string is returned as the final element

    of the list."""

    return _compile(pattern, flags).split(string, maxsplit)

二、一个计算题的实现

用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-25/3 + 7 /399/42998 +10 * 568/14 )) - (-43)/ (16-32) )等类似公式后,自己解析里面的(),+,-,,/符号和公式(不调用eval等类似功能实现),运算后得出结果,结果必须与真实的计算器所得出的结果一致

#!/usr/bin/env python
# -*- coding:utf-8 -*- import re parser_str = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
#完成 def deal_mul_divi(string):
"""
处理乘除法
只处理传过来的字符串,每次处理一个,返回字符串
:param string: 字符串格式严格要求为 25/-5 或 34*3 这样,否则返回None
:return: 返回处理后的结果字符串
"""
res1 = re.search('\d+\.?\d*\/(\-|\d+\.?\d*)+',string)
res2 = re.search('\d+\.?\d*\*(\-|\d+\.?\d*)+',string)
if not res1 and not res2:
print('格式有误:{}'.format(string))
return None
else:
items = re.findall('\d+\.?\d*', string)
result = str(float(items[0])/float(items[1])) \
if res1 else str(float(items[0])*float(items[1]))
#如果字符串中有- 负号,那就增加标记值,让返回值为负 re.search('-', string)同下 '-' in
result = '-{}'.format(result) if '-' in string else result
return result #完成
def deal_plus_minus(string):
"""
将没有乘除号的带(不带)括号都行的字符串传入。该函数先处理字符串中所有负数:(40-4+34)
再处理所有正数,再用正数减负数值作为结果返回,操作皆为浮点数。
:param string: 参数为只有 + - 号的算式
:return:
"""
if re.search('\*|\/', string): #如果有乘除号视为错误
return None
num_minus = 0
for minus in re.findall('\-(\d+\.?\d*)', string): #将所有负数找出来并加起来
string = string.replace(minus, 'sep') #所有前面带减号的数,都将被sep 符替换
num_minus += float(minus)
num_plus = 0
for plus in re.findall('(\d+\.?\d*)', string): #匹配正数相加 #|\+(\d+\.?\d*)
num_plus += float(plus)
return str(num_plus - num_minus)
#完成 def match_brackets(string):
"""
匹配算式中的括号,并调用函数处理
:param string: 算式字符串
:return:
"""
flag = True
while flag:
brackets_str = re.search('\((\+|\-|\.|\/|\*|\d)+\)', string) #拿到括号字符串
if not brackets_str:
flag = False
continue
else:
result = deal_brackets(brackets_str.group()) #调用处理括号函数,处理返回
# print('\033[33;1m{}\033[0m'.format(string))
string = string.replace(brackets_str.group(), result, 1) #将计算原括号得到的结果替换原括号
# print('\033[34;1m{}\033[0m'.format(string))
string = re.sub('(\+\-)|(\-\+)', '-', string) #处理 +- 号和 -+ 并排一起
string = re.sub('--', '+', string) #处理 -- 两减号并排
return string def deal_brackets(string):
"""
处理传过来的括号
:param string:
:return:
"""
flag = True while flag:
# ( -3.2/-1.6-2-3*-2)这样的也要能匹配得 3.2/-1.6
mul_divi_str = re.search('(\d+\.?\d*)(\*|\/)(\-|\d+\.?\d*){1,2}', string) #只能匹配一到两位如 - 1.6
if not mul_divi_str:
flag = False
break
else:
# print('\033[31;4m处理传来的乘除:{}\033[0m'.format(mul_divi_str.group()))
mul_divi_res = deal_mul_divi(mul_divi_str.group())
string = string.replace(mul_divi_str.group(), mul_divi_res, 1)
string = re.sub('(\+\-)|(\-\+)', '-', string) # 处理 +- 号和 -+ 并排一起
string = re.sub('--', '+', string) # 处理 -- 两减号并排
return deal_plus_minus(string) #calculate函数就可以计算任意一个表达式的值了
def calculate(string):
strip_space = lambda x: re.sub(' ', '', x, count=x.count(' ')) #将算式中的所有空格剔除
string = strip_space(string)
string = match_brackets(string) #处理完表达式所有的的括号
result = deal_brackets(string) #在把没有括号的表达式交给它处理一次
return result print('\033[31;1meval:\033[0m{: >22}'.format(eval(parser_str))) #eval 验证结果
print('\033[32;2mcalculate:\033[0m{}'.format(calculate(parser_str))) #正则计算 #运算结果为
eval: 2776672.6952380957
calculate:2776672.6952380957

python 中的re模块,正则表达式的更多相关文章

  1. Python中的re模块--正则表达式

    Python中的re模块--正则表达式 使用match从字符串开头匹配 以匹配国内手机号为例,通常手机号为11位,以1开头.大概是这样13509094747,(这个号码是我随便写的,请不要拨打),我们 ...

  2. python中的re模块——正则表达式

    re模块:正则表达式 正则表达式:为匹配字符 import re #导入re模块 #re.findall('正则表达式','被匹配字符') re模块下findall用法 在正则表达式中: \w 表示匹 ...

  3. 常用正则表达式与python中的re模块

    正则表达式是一种通用的字符串匹配技术,不会因为编程语言不一样而发生变化. 部分常用正则表达式规则介绍: . 匹配任意的一个字符串,除了\n * 匹配任意字符串0次或者任意次 \w 匹配字母.数字.下划 ...

  4. Python中的random模块,来自于Capricorn的实验室

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  5. Python中的logging模块

    http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...

  6. Python中的random模块

    Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...

  7. 浅析Python中的struct模块

    最近在学习python网络编程这一块,在写简单的socket通信代码时,遇到了struct这个模块的使用,当时不太清楚这到底有和作用,后来查阅了相关资料大概了解了,在这里做一下简单的总结. 了解c语言 ...

  8. python中的StringIO模块

    python中的StringIO模块 标签:python StringIO 此模块主要用于在内存缓冲区中读写数据.模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中.此类中的大部分 ...

  9. python中的select模块

    介绍: Python中的select模块专注于I/O多路复用,提供了select  poll  epoll三个方法(其中后两个在Linux中可用,windows仅支持select),另外也提供了kqu ...

  10. python中的shutil模块

    目录 python中的shutil模块 目录和文件操作 归档操作 python中的shutil模块 shutil模块对文件和文件集合提供了许多高级操作,特别是提供了支持文件复制和删除的函数. 目录和文 ...

随机推荐

  1. 使用Navicat for Mysql连接mysql服务器

    使用Navicat for Mysql连接mysql服务器 在windows上用Navicat for Mysql 连接装在虚拟机Ubuntu上的mysql服务器时出现的问题的解决方案. Navica ...

  2. miui10 傻瓜式安装google框架方法

    miui10,打开自带的小米应用商店,搜索youtube,然后往下看选择百度的搜索源,点进去选择第一个下载就可以了. 下载完成之后会就提醒你安装google框架了, 点确定后自动就装好了,就是这么简单 ...

  3. PHP使用Apache中的ab(ApacheBench)测试网站的并发量

    AB(ApacheBench) 是 Apache 自带的超文本传输协议 (HTTP) 性能测试工具. 其设计意图是描绘当前所安装的 Apache 的执行性能, 主要是显示 Apache 每秒可以处理多 ...

  4. 注入攻击(SQL注入)

    注入攻击是web安全领域中一种最为常见的攻击方式.注入攻击的本质,就是把用户输入的数据当做代码执行.这里有两个关键条件,第一是用户能够控制输入,第二个就是原本程序要执行的代码,将用户输入的数据进行了拼 ...

  5. SQLServer插入数据

    使用数据库管理工具插入数据 打开数据库,选则要插入数据的表->右键点击->选择插入前200行->在右边视图中输入要插入的数据(如果字段设置为不为空,则必须输入,如果字段设置为可空,则 ...

  6. 聚类——GAKFCM的matlab程序

    聚类——GAKFCM的matlab程序 作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 在聚类——GAKFCM文章中已介绍了GAKFCM算法的理论知识, ...

  7. MATLAB求解二重积分案例

    凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/ 定积分解决的是一维连续量求和的问题,而解决多维连续量的求和问题就要用到重积分了.重积分是建立在定积分的基础上的 ...

  8. 【文学文娱】《屌丝逆袭》-出任CEO、迎娶白富美、走上人生巅峰

    本文地址:http://www.cnblogs.com/aiweixiao/p/7759790.html 原文地址:(微信公众号) 原创 2017-10-30 微信号wozhuzaisi 程序员的文娱 ...

  9. centos7下安装docker(25docker swarm---replicated mode&global mode)

    swarm可以在service创建或运行过程中灵活的通过--replicas调整容器的副本数量,内部调整调度器则会根据当前集群资源使用的情况在不同的node上启动或停止容器,这就是service默认的 ...

  10. re库

    一.Re库的主要功能: 函数 功能 re.search() 在一个字符串中搜索匹配正则表达式的第一个位置,返回match对象 re.match() 在一个字符串的开始位置匹配正则表达式,返回match ...