python 中的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模块,正则表达式的更多相关文章
- Python中的re模块--正则表达式
Python中的re模块--正则表达式 使用match从字符串开头匹配 以匹配国内手机号为例,通常手机号为11位,以1开头.大概是这样13509094747,(这个号码是我随便写的,请不要拨打),我们 ...
- python中的re模块——正则表达式
re模块:正则表达式 正则表达式:为匹配字符 import re #导入re模块 #re.findall('正则表达式','被匹配字符') re模块下findall用法 在正则表达式中: \w 表示匹 ...
- 常用正则表达式与python中的re模块
正则表达式是一种通用的字符串匹配技术,不会因为编程语言不一样而发生变化. 部分常用正则表达式规则介绍: . 匹配任意的一个字符串,除了\n * 匹配任意字符串0次或者任意次 \w 匹配字母.数字.下划 ...
- Python中的random模块,来自于Capricorn的实验室
Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...
- Python中的logging模块
http://python.jobbole.com/86887/ 最近修改了项目里的logging相关功能,用到了python标准库里的logging模块,在此做一些记录.主要是从官方文档和stack ...
- Python中的random模块
Python中的random模块用于生成随机数.下面介绍一下random模块中最常用的几个函数. random.random random.random()用于生成一个0到1的随机符点数: 0 < ...
- 浅析Python中的struct模块
最近在学习python网络编程这一块,在写简单的socket通信代码时,遇到了struct这个模块的使用,当时不太清楚这到底有和作用,后来查阅了相关资料大概了解了,在这里做一下简单的总结. 了解c语言 ...
- python中的StringIO模块
python中的StringIO模块 标签:python StringIO 此模块主要用于在内存缓冲区中读写数据.模块是用类编写的,只有一个StringIO类,所以它的可用方法都在类中.此类中的大部分 ...
- python中的select模块
介绍: Python中的select模块专注于I/O多路复用,提供了select poll epoll三个方法(其中后两个在Linux中可用,windows仅支持select),另外也提供了kqu ...
- python中的shutil模块
目录 python中的shutil模块 目录和文件操作 归档操作 python中的shutil模块 shutil模块对文件和文件集合提供了许多高级操作,特别是提供了支持文件复制和删除的函数. 目录和文 ...
随机推荐
- WebClient图片下载
使用WebClient下载文件非常方便,针对有部分网站通过请求头的Referer,做了图片防盗链,可以在webClient加上Referer 来模拟请求 string basePath = Path. ...
- C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法
使用反射(Reflect)获取dll文件中的类型并调用方法 需引用:System.Reflection; 1. 使用反射(Reflect)获取dll文件中的类型并调用方法(入门案例) static v ...
- 处理HTML5新标签的浏览器兼容问题
<!--[if lt IE 9]> <script type="text/javascript" src="js/html5shiv.js"& ...
- CF917D Stranger Trees
CF917D Stranger Trees 题目描述 给定一个树,对于每个\(k=0,1\cdots n-1\),问有多少个生成树与给定树有\(k\)条边重合. 矩阵树定理+高斯消元 我们答案为\(f ...
- TFT1.44显示屏
下载这个库 普通arduino的接口 链接 UTFT myGLCD(LPH9135,6,5,2,3,4); mega2560的接口连接 UTFT myGLCD(QD_TFT180A,A2,A1,A5, ...
- Eclipse下关于The serializable class UsersServlet does not declare a static final serialVersionUID field of type的警告
The serializable class XXX does not declare a static final serialVersionUID field of type long seria ...
- Java NIO4:缓冲区Buffer(续)
一.什么是缓冲区 一个缓冲区对象是固定数量的数据的容器,其作用是一个存储器,或者分段运输区,在这里数据可被存储并在之后用于检索.缓冲区像前篇文章讨论的那样被写满和释放,对于每个非布尔原始数据 ...
- 环境部署(七):linux下Jenkins+Git+JDK持续集成
前面几篇博客介绍了linux下安装Jenkins.Git.JDK以及Git基础教程和Git关联github等内容,这篇博客,介绍下如何在linux服务器中利用它们构建持续集成环境... 一.准备工作 ...
- oracle expdp导出时报 ora-39070:无法打开日志文件
在通过expdp导出命令导出某个用户的对象时出现以下截图错误: ORA-39002:操作无效 ORA-39070:无法打开日志文件 ORA-39087:目录名<directory>无效 该 ...
- PowerMock单元测试踩坑与总结
1.Mock是什么? 通过提供定制的类加载器以及一些字节码篡改技巧的应用,PowerMock 现了对静态方法.构造方法.私有方法以及 Final 方法的模拟支持,对静态初始化过程的移除等强大的功能. ...