当前位置:网站首页>5分钟包你学会正则表达式
5分钟包你学会正则表达式
2022-06-26 05:39:00 【上海一亩地】
正则表达式的作用:
用一个pattern字符串去匹配目标字符串中相似的某一段。说白了,哪天你看到一个字符串,你想要从里面抠出来一段,你就用正则表达式把你要的这一段匹配出来
编写正则的步骤
1.先打好结构体。固定的东西直接写,不固定的会变化的用圆括号代替。
案例1:
比如有一类字符串
“admin-api-8xd5sdfa9p-asdf4”
“admin-api-qos3difd1c-2q5gh”
如何匹配这类字符串?
先打好结构体:”admin-api-()-()” ,这样就好了。不变的直接写,变化的用圆括号代替,这就是结构体。
案例2:
比如从字符串中找出11位的手机号码
目标字符串是:”姓名:张伟;电话:13011348290”
我们只想匹配电话号码,其他的不要。电话号码11位都是不固定的。
那么结构体就是一对圆括号 “()” ,就这么回事。
2.在下方的速查表中找到你需要的正则字符填到结构体中
正则字符分为两类,一类是表示内容的,一类表示出现的次数的。
比如 . 属于内容字符,*表示次数字符 ,那么 .* 就表示任意内容任意长度字符串。这是最常用的。
比如 [0-9] 表示0-9中的某一个数字,是内容字符,{11}表示出现11次,{10,20}表示出现10次到20次,这些就是次数字符。所以[0-9]{11}就能匹配连续11位数字,即电话号码。
所以上方的两个案例完整的正则表达式是这样:
“admin-api-(\w{10})-(\w{5})”
“(\d{11})” 或者 “([0-9]{11})”
3.(选读)Python使用正则表达式匹配字符串的一般代码
import re # re是python标准库的功能模块,相当于java中的Maven包
pattern = re.compile(“admin-api-(\w{
10})-(\w{
5})”) # 将你写好的正则表达式编译一下,执行速度快
groups = pattern.match(“目标字符串,比如admin-api-8xd5sdfa9p-asdf4”)
# groups是一个列表,第一个元素是匹配到的最长的字符串,然后后面的元素依次是第一个圆括号的匹配内容、第二个圆括号匹配到的内容……
# match函数是从头匹配,如果你想匹配的字符串不是在目标字符串的开头,则用groups = pattern.findall()
print(groups[0]) # 打印你匹配到的最长完整字符串,这里应该是 admin-api-8xd5sdfa9p-asdf4
print(groups[1]) # 第一个圆括号匹配到的字符串,这里应该是 8xd5sdfa9p
正则速查表
结构体中()表示变化的部分,下表还展示了(?: ) (?=) (?!)的用法。
边栏推荐
- uniCloud云开发获取小程序用户openid
- REUSE_ALV_GRID_DISPLAY 事件实现(DATA_CHANGED)
- 使用Jedis监听Redis Stream 实现消息队列功能
- Henkel database custom operator '~~‘
- Pytorch中自己所定义(修改)的模型加载所需部分预训练模型参数并冻结
- 睛天霹雳的消息
- Mise en file d'attente des messages en utilisant jedis Listening redis stream
- Could not get unknown property ‘*‘ for SigningConfig container of type org. gradle. api. internal
- Written before father's Day
- ZigBee explain in simple terms lesson 2 hardware related and IO operation
猜你喜欢
Sofa weekly | open source person - Yu Yu, QA this week, contributor this week
Ad tutorial series | 4 - creating an integration library file
【C語言】深度剖析數據在內存中的存儲
Gram 矩阵
使用Jenkins执行TestNg+Selenium+Jsoup自动化测试和生成ExtentReport测试报告
The difference between get and post in small interview questions
慢慢学JVM之缓存行和伪共享
【C语言】深度剖析数据在内存中的存储
The localstorage browser stores locally to limit the number of forms submitted when tourists do not log in.
转帖——不要迷失在技术的海洋中
随机推荐
Leetcode114. 二叉树展开为链表
Redis discovery bloom filter
BOM文档
The news of thunderbolt
How to ensure the efficiency and real-time of pushing large-scale group messages in mobile IM?
June 3 is a happy day
How does P2P technology reduce the bandwidth of live video by 75%?
Redis usage and memory optimization
vscode config
Consul服务注册与发现
Pre-Sale Analysis
Replacing domestic image sources in openwrt for soft routing (take Alibaba cloud as an example)
[upsampling method opencv interpolation]
力扣 875. 爱吃香蕉的珂珂
Leetcode513. Find the value in the lower left corner of the tree
Posting - don't get lost in the ocean of Technology
Positioning setting horizontal and vertical center (multiple methods)
Feelings of virtual project failure
[arm] build boa based embedded web server on nuc977
【MYSQL】MySQL 百万级数据量分页查询方法及其优化