再见,正则表达式(再见的正式说法)
ztj100 2024-11-06 13:18 11 浏览 0 评论
从一段指定的字符串中,取得期望的数据,正常人都会想到正则表达式吧?
写过正则表达式的人都知道,正则表达式入门不难,写起来也容易。
但是正则表达式几乎没有可读性可言,维护起来,真的会让人抓狂,别以为这段正则是你写的就可以驾驭它,过个一个月你可能就不认识它了。
完全可以说,天下苦正则久矣。
今天给你介绍一个好东西,可以让你摆脱正则的噩梦,那就是 Python 中一个非常冷门的库 -- parse
。
1. 真实案例
拿一个最近使用 parse 的真实案例来举例说明。
下面是 ovs 一个条流表,现在我需要收集提取一个虚拟机(网口)里有多少流量、多少包流经了这条流表。也就是每个 in_port 对应的 n_bytes、n_packets 的值 。
cookie=0x9816da8e872d717d, duration=298506.364s, table=0, n_packets=480, n_bytes=20160, priority=10,ip,in_port="tapbbdf080b-c2" actions=NORMAL
如果是你,你会怎么做呢?
先以逗号分隔开来,再以等号分隔取出值来?
你不防可以尝试一下,写出来的代码应该和我想象的一样,没有一丝美感而言。
我来给你展示一下,我是怎么做的?
可以看到,我使用了一个叫做 parse 的第三方包,是需要自行安装的
$ python -m pip install parse
从上面这个案例中,你应该能感受到 parse 对于解析规范的字符串,是非常强大的。
2. parse 的结果
parse 的结果只有两种结果:
没有匹配上,parse 的值为None
>>> parse("halo", "hello") is None
True
>>>
如果匹配上,parse 的值则 为 Result 实例
>>> parse("hello", "hello world")
>>> parse("hello", "hello")
<Result {}>
>>>
如果你编写的解析规则,没有为字段定义字段名,也就是匿名字段, Result 将是一个 类似 list 的实例,演示如下:
>>> profile = parse("I am {}, {} years old, {}", "I am Jack, 27 years old, male")
>>> profile
<Result ('Jack', '27', 'male') {}>
>>> profile[0]
'Jack'
>>> profile[1]
'27'
>>> profile[2]
'male'
而如果你编写的解析规则,为字段定义了字段名, Result 将是一个 类似 字典 的实例,演示如下:
>>> profile = parse("I am {name}, {age} years old, {gender}", "I am Jack, 27 years old, male")
>>> profile
<Result {'gender': 'male', 'age': '27', 'name': 'Jack'}>
>>> profile['name']
'Jack'
>>> profile['age']
'27'
>>> profile['gender']
'male'
3. 重复利用 pattern
和使用 re 一样,parse 同样支持 pattern 复用。
>>> from parse import compile
>>>
>>> pattern = compile("I am {}, {} years old, {}")
>>> pattern.parse("I am Jack, 27 years old, male")
<Result ('Jack', '27', 'male') {}>
>>>
>>> pattern.parse("I am Tom, 26 years old, male")
<Result ('Tom', '26', 'male') {}>
4. 类型转化
从上面的例子中,你应该能注意到,parse 在获取年龄的时候,变成了一个"27"
,这是一个字符串,有没有一种办法,可以在提取的时候就按照我们的类型进行转换呢?
你可以这样写。
>>> from parse import parse
>>> profile = parse("I am {name}, {age:d} years old, {gender}", "I am Jack, 27 years old, male")
>>> profile
<Result {'gender': 'male', 'age': 27, 'name': 'Jack'}>
>>> type(profile["age"])
<type 'int'>
除了将其转为 整型,还有其他格式吗?
内置的格式还有很多,比如
匹配时间
>>> parse('Meet at {:tg}', 'Meet at 1/2/2011 11:00 PM')
<Result (datetime.datetime(2011, 2, 1, 23, 0),) {}>
更多类型请参考官方文档:
Type | Characters Matched | Output |
---|---|---|
l | Letters (ASCII) | str |
w | Letters, numbers and underscore | str |
W | Not letters, numbers and underscore | str |
s | Whitespace | str |
S | Non-whitespace | str |
d | int | |
D | Non-digit | str |
n | int | |
% | Percentage (converted to value/100.0) | float |
f | Fixed-point numbers | float |
F | Decimal numbers | Decimal |
e | float | |
g | General number format (either d, f or e) | float |
b | Binary numbers | int |
o | Octal numbers | int |
x | int | |
ti | ISO 8601 format date/time e.g. 1972-01-20T10:21:36Z (“T” and “Z” optional) | datetime |
te | datetime | |
tg | Global (day/month) format date/time e.g. 20/1/1972 10:21:36 AM +1:00 | datetime |
ta | datetime | |
tc | ctime format date/time e.g. Sun Sep 16 01:03:52 1973 | datetime |
th | datetime | |
ts | Linux system log format date/time e.g. Nov 9 03:37:44 | datetime |
tt | Time e.g. 10:21:36 PM -5:30 | time |
5. 提取时去除空格
去除两边空格
>>> parse('hello {} , hello python', 'hello world , hello python')
<Result (' world ',) {}>
>>>
>>>
>>> parse('hello {:^} , hello python', 'hello world , hello python')
<Result ('world',) {}>
去除左边空格
>>> parse('hello {:>} , hello python', 'hello world , hello python')
<Result ('world ',) {}>
去除右边空格
>>> parse('hello {:<} , hello python', 'hello world , hello python')
<Result (' world',) {}>
6. 大小写敏感开关
Parse 默认是大小写不敏感的,你写 hello 和 HELLO 是一样的。
如果你需要区分大小写,那可以加个参数,演示如下:
>>> parse('SPAM', 'spam')
<Result {}>
>>> parse('SPAM', 'spam') is None
False
>>> parse('SPAM', 'spam', case_sensitive=True) is None
True
7. 匹配字符数
精确匹配:指定最大字符数
>>> parse('{:.2}{:.2}', 'hello') # 字符数不符
>>>
>>> parse('{:.2}{:.2}', 'hell') # 字符数相符
<Result ('he', 'll') {}>
模糊匹配:指定最小字符数
>>> parse('{:.2}{:2}', 'hello')
<Result ('h', 'ello') {}>
>>>
>>> parse('{:2}{:2}', 'hello')
<Result ('he', 'llo') {}>
若要在精准/模糊匹配的模式下,再进行格式转换,可以这样写
>>> parse('{:2}{:2}', '1024')
<Result ('10', '24') {}>
>>>
>>>
>>> parse('{:2d}{:2d}', '1024')
<Result (10, 24) {}>
8. 三个重要属性
Parse 里有三个非常重要的属性
fixed:利用位置提取的匿名字段的元组
named:存放有命名的字段的字典
spans:存放匹配到字段的位置
下面这段代码,带你了解他们之间有什么不同
>>> profile = parse("I am {name}, {age:d} years old, {}", "I am Jack, 27 years old, male")
>>> profile.fixed
('male',)
>>> profile.named
{'age': 27, 'name': 'Jack'}
>>> profile.spans
{0: (25, 29), 'age': (11, 13), 'name': (5, 9)}
>>>
9. 自定义类型的转换
匹配到的字符串,会做为参数传入对应的函数
比如我们之前讲过的,将字符串转整型
>>> parse("I am {:d}", "I am 27")
<Result (27,) {}>
>>> type(_[0])
<type 'int'>
>>>
其等价于
>>> def myint(string):
... return int(string)
...
>>>
>>>
>>> parse("I am {:myint}", "I am 27", dict(myint=myint))
<Result (27,) {}>
>>> type(_[0])
<type 'int'>
>>>
利用它,我们可以定制很多的功能,比如我想把匹配的字符串弄成全大写
>>> def shouty(string):
... return string.upper
...
>>> parse('{:shouty} world', 'hello world', dict(shouty=shouty))
<Result ('HELLO',) {}>
>>>
10 总结一下
parse 库在字符串解析处理场景中提供的便利,肉眼可见,上手简单。
在一些简单的场景中,使用 parse 可比使用 re 去写正则开发效率不知道高几个 level,用它写出来的代码富有美感,可读性高,后期维护起代码来一点压力也没有,推荐你使用。
(完)
Python学习交流群
为了让大家更加即时地沟通学习,我们建了一个Python学习交流群,有想入群的同学,可以添加下面小助手微信,他会拉大家入群哈~
相关推荐
- Vue 技术栈(全家桶)(vue technology)
-
Vue技术栈(全家桶)尚硅谷前端研究院第1章:Vue核心Vue简介官网英文官网:https://vuejs.org/中文官网:https://cn.vuejs.org/...
- vue 基础- nextTick 的使用场景(vue的nexttick这个方法有什么用)
-
前言《vue基础》系列是再次回炉vue记的笔记,除了官网那部分知识点外,还会加入自己的一些理解。(里面会有部分和官网相同的文案,有经验的同学择感兴趣的阅读)在开发时,是不是遇到过这样的场景,响应...
- vue3 组件初始化流程(vue组件初始化顺序)
-
学习完成响应式系统后,咋们来看看vue3组件的初始化流程既然是看vue组件的初始化流程,咋们先来创建基本的代码,跑跑流程(在app.vue中写入以下内容,来跑流程)...
- vue3优雅的设置element-plus的table自动滚动到底部
-
场景我是需要在table最后添加一行数据,然后把滚动条滚动到最后。查网上的解决方案都是读取html结构,暴力的去获取,虽能解决问题,但是不喜欢这种打补丁的解决方案,我想着官方应该有相关的定义,于是就去...
- Vue3为什么推荐使用ref而不是reactive
-
为什么推荐使用ref而不是reactivereactive本身具有很大局限性导致使用过程需要额外注意,如果忽视这些问题将对开发造成不小的麻烦;ref更像是vue2时代optionapi的data的替...
- 9、echarts 在 vue 中怎么引用?(必会)
-
首先我们初始化一个vue项目,执行vueinitwebpackechart,接着我们进入初始化的项目下。安装echarts,npminstallecharts-S//或...
- 无所不能,将 Vue 渲染到嵌入式液晶屏
-
该文章转载自公众号@前端时刻,https://mp.weixin.qq.com/s/WDHW36zhfNFVFVv4jO2vrA前言...
- vue-element-admin 增删改查(五)(vue-element-admin怎么用)
-
此篇幅比较长,涉及到的小知识点也比较多,一定要耐心看完,记住学东西没有耐心可不行!!!一、添加和修改注:添加和编辑用到了同一个组件,也就是此篇文章你能学会如何封装组件及引用组件;第二能学会async和...
- 最全的 Vue 面试题+详解答案(vue面试题知识点大全)
-
前言本文整理了...
- 基于 vue3.0 桌面端朋友圈/登录验证+60s倒计时
-
今天给大家分享的是Vue3聊天实例中的朋友圈的实现及登录验证和倒计时操作。先上效果图这个是最新开发的vue3.x网页端聊天项目中的朋友圈模块。用到了ElementPlus...
- 不来看看这些 VUE 的生命周期钩子函数?| 原力计划
-
作者|huangfuyk责编|王晓曼出品|CSDN博客VUE的生命周期钩子函数:就是指在一个组件从创建到销毁的过程自动执行的函数,包含组件的变化。可以分为:创建、挂载、更新、销毁四个模块...
- Vue3.5正式上线,父传子props用法更丝滑简洁
-
前言Vue3.5在2024-09-03正式上线,目前在Vue官网显最新版本已经是Vue3.5,其中主要包含了几个小改动,我留意到日常最常用的改动就是props了,肯定是用Vue3的人必用的,所以针对性...
- Vue 3 生命周期完整指南(vue生命周期及使用)
-
Vue2和Vue3中的生命周期钩子的工作方式非常相似,我们仍然可以访问相同的钩子,也希望将它们能用于相同的场景。...
- 救命!这 10 个 Vue3 技巧藏太深了!性能翻倍 + 摸鱼神器全揭秘
-
前端打工人集合!是不是经常遇到这些崩溃瞬间:Vue3项目越写越卡,组件通信像走迷宫,复杂逻辑写得脑壳疼?别慌!作为在一线摸爬滚打多年的老前端,今天直接甩出10个超实用的Vue3实战技巧,手把...
- 怎么在 vue 中使用 form 清除校验状态?
-
在Vue中使用表单验证时,经常需要清除表单的校验状态。下面我将介绍一些方法来清除表单的校验状态。1.使用this.$refs...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- Vue 技术栈(全家桶)(vue technology)
- vue 基础- nextTick 的使用场景(vue的nexttick这个方法有什么用)
- vue3 组件初始化流程(vue组件初始化顺序)
- vue3优雅的设置element-plus的table自动滚动到底部
- Vue3为什么推荐使用ref而不是reactive
- 9、echarts 在 vue 中怎么引用?(必会)
- 无所不能,将 Vue 渲染到嵌入式液晶屏
- vue-element-admin 增删改查(五)(vue-element-admin怎么用)
- 最全的 Vue 面试题+详解答案(vue面试题知识点大全)
- 基于 vue3.0 桌面端朋友圈/登录验证+60s倒计时
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)