当前位置:网站首页>速刷正则表达式一周目(上)
速刷正则表达式一周目(上)
2022-08-10 05:29:00 【我不叫内谁】
目录
前言:在文本查找方面,你可能很熟悉ctrlF,输入你想要查找的词。但正则表达式在此基础上更进一步,它可以通过位置、模式以及通配符等进行快速查找。本篇文章将以千字左右篇幅,带你速刷正则表达式的一些简单内容以及实战。
一、不使用正则表达式筛选电话号码
众所周知,电话号码由三部分组成,例如:132-3233-7777,是由3位网号+4位HLR号+4位的个人代码。假定我们构建一个函数,筛选广电号段的电话号码(中国广电号段:192),有如下操作
def phoneNumber(text):#1
if len(text) != 11:#2
return False
if text[0:3] != '192':#3
return False
for i in range(0,11):#4
if not text[i].isdecimal():#4
return False
return True
print(phoneNumber('12345557656'))
print(phoneNumber('19233333333'))
首先#1使用def定义函数phoneNumber(),#2判断文本长度是否等于11位,若不等于,则返回False。#3遍历文本前三位,如果不等于192,则返回False,#4遍历全11位,如果不是纯数字,则返回False。
输出如下:
可以看到相当麻烦,接下来,以正则表达式查找文本。
二、使用正则表达式筛选电话号码
创建正则表达式对象
import re
phoneNumber = re.compile(r'1\d\d\d\d\d\d\d\d\d\d')
mo = phoneNumber.search('My number is 17543405207')
print("My phone number is " + mo.group())#变量名mo是一个通用的名称
输出如下
复习:
第一步:使用import re导入正则表达式模块。
第二步:用re.compile()函数创建一个Regex对象(使用原始字符串)。
第三步:想Regex对象的search()方法传入想查找的字符串。它返回一个Match对象。
第四步:调用Match对象的group()方法,返回实际匹配文本的字符串。
三、利用括号分组
import re
phoneNumber = re.compile(r'(\d\d\d)-(\d\d\d\d-\d\d\d\d)')
mo = phoneNumber.search('My phone number is 175-4340-5207')
mo.group(1)
mo.group(0)
mo.group(2)
输出如下
如果需要一次获取全部分组,使用groups()
四、用管道匹配多个分组
字符|被称为管道,希望匹配许多表达式中的一个时,可以有如下操作
color = re.compile(r'red|blue')
mo1 = color.search('red and blue')
mo1.group()
mo2 = color.search('blue and red')
mo2.group()
如果希望匹配'Batman'、'Batmobile'、'Batcopter'
bat = re.compile(r'Bat(man|mobile|copter)')
mo = bat.search('Batmobile lost a wheel')
mo.group()
mo.group(1)
dio用mo.group()返回完全匹配的文本'Batmobile',而mo.group(1)只是返回了第一个括号分组内的文本'mobile'
如果需要匹配真正的管道字符,就要用到转义字符。
附
正则表达式相对重要,推荐刷题网站:牛客网 - 找工作神器|笔试题库|面试经验|实习招聘内推,求职就业一站解决_牛客网
边栏推荐
- 图纸怎么折?(A0,A1,A2,A3の图纸如何折成A4大小)
- k-近邻实现手写数字识别
- 虚拟土地价格暴跌85% 房地产泡沫破裂?依托炒作的暴富游戏需谨慎参与
- FPGA engineer interview questions collection 21~30
- Qiskit官方文档选译之量子傅里叶变换(Quantum Fourier Transform, QFT)
- Concurrency tool class - introduction and use of CountDownLatch, CyclicBarrier, Semaphore, Exchanger
- scikit-learn机器学习 读书笔记(一)
- pytorch框架学习(5)torchvision模块&训练一个简单的自己的CNN (二)
- 基于Qiskit——《量子计算编程实战》读书笔记(七)
- scikit-learn机器学习 读书笔记(二)
猜你喜欢
随机推荐
Rpc interface stress test
Order table delete, insert and search operations
flex related
WSTP初体验
Practical skills 19: Several postures of List to Map List
Why are negative numbers in binary represented in two's complement form - binary addition and subtraction
pytorch learning
MySQL simple tutorial
EasyGBS connects to mysql database and prompts "can't connect to mysql server", how to solve it?
【LeetCode】41. The first missing positive number
How to simulate the background API call scene, very detailed!
手把手带你写嵌入式物联网的第一个项目
MySql's json_extract function processes json fields
You can‘t specify target table ‘kms_report_reportinfo‘ for update in FROM clause
SSM框架整合实例
树莓派入门(3)树莓派GPIO学习
Linear Algebra (4)
pytorch 学习
How to improve product quality from the code layer
如何用Apifox 的智能Mock功能?