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模块对文件和文件集合提供了许多高级操作,特别是提供了支持文件复制和删除的函数. 目录和文 ...
随机推荐
- win8系统电脑自动关机怎么取消
在使用win8系统的用户会遇到电脑自动关机的情况,这是win8自带的自动关机功能,如果想取消这个功能,只需要通过执行一个命令即可实现.下面小编来为大家讲解一下具体步骤. 1.组合键:win+R,然后在 ...
- JavaScript -- 时光流逝(四):js中的 Math 对象的属性和方法
JavaScript -- 知识点回顾篇(四):js中的 Math 对象的属性和方法 1. Math 对象的属性 (1) E :返回算术常量 e,即自然对数的底数(约等于2.718). (2) LN2 ...
- Java教程01-基础语法
目录 1. 基本概念 1.1. 环境变量 Path环境变量的作用->寻找命令 classpath变量的作用->寻找类文件 1.2. JDK里面有什么? 1.3. 什么是JRE? 2. Ja ...
- 团队作业—预则立&&他山之石
团队作业-预则立&&他山之石 Deadline: 2017.10.24 22:00pm 作业要求 一.确立团队选题,建立和初步熟悉团队git的协作方式.项目后续的代码.文档都要通过gi ...
- 汲取营养的blog专栏
网路上博客专栏是学习提升.思考深化的好途径,目前发现的博客价值高的平台: (1)EETOP www.eetop.cn (2)CSND www.csdn.net (3)cnblog www.cnblog ...
- ORCFILE IN HDP 2: BETTER COMPRESSION, BETTER PERFORMANCE
ORCFILE IN HDP 2: BETTER COMPRESSION, BETTER PERFORMANCE by Carter Shanklin The upcoming Hive 0.12 ...
- 基于diango简易BLOG图片预览
注册界面 登陆界面 博客主界面 个人站点主页 文章详情页 个人博客后台 添加文章页 修改密码页
- SQL Server 数据导入Mysql具体教程
SQLServer2005数据导入Mysql到具体教程(測试) SQL SERVER数据导入MYSQL文件夹 1.Navicat for MySQL 版本号10.0.9 2.创建目标数据库 3.创 ...
- 机器学习算法总结(三)——集成学习(Adaboost、RandomForest)
1.集成学习概述 集成学习算法可以说是现在最火爆的机器学习算法,参加过Kaggle比赛的同学应该都领略过集成算法的强大.集成算法本身不是一个单独的机器学习算法,而是通过将基于其他的机器学习算法构建多个 ...
- KazaQ's Socks (找规律)
#include<iostream> using namespace std; #define ll long long ll n, m; ll t; int main(){ while ...