1. 程式人生 > >完整的正則表達式知識匯總(Python知識不斷更新)

完整的正則表達式知識匯總(Python知識不斷更新)

們的 技術分享 web 固定 vpd oss html5 出現 react

## 大綱:

技術分享圖片

## 一、正則概述

1.正則是什麽
正則就是一套規則,或者語法
2.正則的作用
讓我們判斷是否符合我們的的規則,或者根據規則找到符合規則的數據
3.使用場景
可以用正則判斷我們輸入的郵箱是否合法
可以用正則去獲取整個網頁的照片
4.適合語言
所有語言都可以通用

## 二、正則表達式簡單使用

題目:判斷hello是否在helloword中存在
步驟:
1.導入包
2.使用正則匹配
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20181113200131709.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTYzNTMwNQ==,size_16,color_FFFFFF,t_70)

## 三、正則規則匯總:

**1. 單字符(一般大寫用的特別少)**
. 匹配任意1個字符(除了\n)
[ ] 匹配[ ]中列舉的字符[ab456c][a-z]
\d 匹配數字,即0-9
\D 匹配非數字,即不是數字
\s 匹配空白,即 空格,tab鍵\t,\n
\S 匹配非空白
\w 匹配單詞字符,即a-z、A-Z、0-9、_,國家的文字
\W 匹配非單詞字符
```
# . 匹配任意1個字符(除了\n)
# --判斷包含速度與激情字符串的
# print(re.match("用戶速度與激情.8", ‘用戶速度與激情 8‘).group())
# print(re.match("用戶速度與激情.", ‘用戶速度與激情_‘).group())

# [ ] 匹配[ ]中列舉的字符[ab456c][a-z]
# 格式1:[單個值,...]
# 判斷用戶只想看1,4,8的速度與激情
print(re.match(‘速度與激情[148]‘, ‘速度與激情4‘).group())
# 格式2:[範圍,...]
# 判斷用戶只看1到8的速度與激情
# print(re.match(‘速度與激情[1-8]‘, ‘速度與激情8‘).group())
# 格式3:[數字字符]
# 判斷用戶輸入的速度與激情1到8或者速度與激情a-h
# print(re.match(‘速度與激情[1-8a-h]‘, ‘速度與激情e‘).group())

# \d 匹配數字,即0-9
# print(re.match(‘用戶速度與激情\d‘, "用戶速度與激情8").group())

# \D 匹配非數字,即不是數字
# print(re.match(‘用戶速度與激情\D‘, "用戶速度與激情\n").group())

# \s 匹配空白,即 空格,tab鍵\t,\n
# --判斷用戶速度與激情 8
# print(re.match("用戶速度與激情\s8", "用戶速度與激情\n8").group())

# \S 匹配非空白
# print(re.match(‘用戶速度與激情\D‘, "用戶速度與激情\n").group())

# \w 匹配單詞字符,即a-z、A-Z、0-9、_,漢字也可以匹配,其他的國家的語言也可以匹配
# 判斷用戶輸入包含速度與激情
# print(re.match("速度與激情\w", "速度與激情四"))
# print(re.match("速度與激情\w", "速度與激情かないで"))

# \W 匹配非單詞字符(用的少)
print(re.match("\W", "&"))

```
**2. 多字符(一般大寫用的特別少)**
\* 匹配前一個字符出現0次或者無限次,即可有可無
\+ 匹配前一個字符出現1次或者無限次,即至少有1次
? 匹配前一個字符出現1次或者0次,即要麽有1次,要麽沒有
{m} 匹配前一個字符出現m次 \d{3}
{m,n} 匹配前一個字符出現從m到n次 \d{4,6}
```
# * 匹配前一個字符出現0次或者無限次,即可有可無
# 表示0或者無限次
# 匹配一段文字或者沒有輸入文字

str = """今天天氣不錯
我們可以出去運動一下!
"""
print(re.match(‘.*‘, str).group())
# re.S 這個讓我們的.匹配所有的數據(即忽略換行,匹配全文)
print(re.match(‘.*‘, str, re.S).group())

# + 匹配前一個字符出現1次或者無限次,即至少有1次,不能為空
print(re.match(‘.+‘, ‘ ‘).group())

# ? 匹配前一個字符出現1次或者0次,即要麽有1次,要麽沒有
# 用來表示有一個字符或者沒有字符
# 用戶輸入的電話號碼有時有‘-‘有時沒有
# 例:02112345678 或者 021-12345678

print(re.match(‘021-?\d{8}‘, ‘021-12345678‘).group())
print(re.match(‘021-?\d{8}‘, ‘02112345678‘).group())

# {m} 匹配前一個字符出現m次 \d{3}
# 判斷電話號碼是否021 - 開頭的後面8位電話號碼
# 例: 021 - 12345678
# 判斷電話號
print(re.match(‘021-\d{8}‘, ‘021-12345678‘).group())

# {m,n} 匹配前一個字符出現從m到n次 \d{4,6}
題目:# 匹配速度與激情1,速度與激情12
print(re.match(‘速度與激情\d{1,2}‘, ‘速度與激情12‘).group())

```
**3. 匹配開頭結尾**
^ 匹配字符串開頭
$ 匹配字符串結尾


**3.1 ^ 匹配字符串開頭**
```
# 需求:匹配以數字開頭的數據
import re

# 匹配以數字開頭的數據
match_obj = re.match("^\d.*", "3hello")
if match_obj:
# 獲取匹配結果
print(match_obj.group())
else:
print("匹配失敗")

運行結果:
3hello
```
**3.2 $ 匹配字符串結尾**

```
# 需求: 匹配以數字結尾的數據

import re
# 匹配以數字結尾的數據
match_obj = re.match(".*\d$", "hello5")
if match_obj:
# 獲取匹配結果
print(match_obj.group())
else:
print("匹配失敗")
運行結果:
hello5
```
**4. 分組**
| 匹配左右任意一個表達式
( ) 將括號中字符作為一個分組
\num 引用分組num匹配到的字符串
(?P<name>) 分組起別名
(?P=name) 引用別名為name分組匹配到的字符串


**4.1. | 或**
\* 匹配前一個字符出現0次或者無限次,即可有可無

```
# | 相當於python中的or
# 案例:匹配出163或者126的郵箱
import re

str = "[email protected]"
str2 = "[email protected]"

# |或者的意思
print(re.match(‘.{4,20}@(163|126)\.com‘, str).group())
print(re.match(‘.{4,20}@(163|126)\.com‘, str2).group())
```

**4.2 ( )還可以單獨取出匹配的某一部分數據**
```
# 案例:取出郵箱的類型(只要163,126),後期可以編計用戶那個郵箱用的多
# str = "[email protected]"

print(re.match(".{4,20}@(163|126)\.com", str).group())
print(re.match(".{4,20}@(163|126)\.com", str).group(0))
print(re.match(".{4,20}@(163|126)\.com", str).group(1))
```
**4.3 \num用來取第幾組用()包裹的數據 \1取第一個內部的括號位置的值**
```
# 格式(xxx)\1 :\1表示獲取(xxx)的值
# 1.案例<html>hh</html> # 這個一定是有字母,開始跟結束的字母必須一樣

print(re.match("<([a-zA-Z]+)>.*</[a-zA-Z]+>", ‘<html>hh</html>‘).group())
print(re.match("<([a-zA-Z]+)>.*</\\1>", ‘<html>hh</html>‘).group(0))


# 2.案例<html><body>hh</body></html>

str = ‘<html><body>hh</body></html>‘
# print(re.match("<([a-zA-Z]+)><[a-zA-Z]+>.*</[a-zA-Z]+></[a-zA-Z]+>", str).group())
# print(re.match("<([a-zA-Z]+)><[a-zA-Z]+>.*</[a-zA-Z]+></[a-zA-Z]+>", str).group(1))
# print(re.match("<([a-zA-Z]+)><([a-zA-Z]+)>.*</[a-zA-Z]+></[a-zA-Z]+>", str).group(2))
# print(re.match("<([a-zA-Z]+)><([a-zA-Z]+)>.*</\\2></\\1>", str).group())
```
**4.4 給分組取別名:(?P<別名>xxx)(?P=別名)**

```
# 使用別名給分組取別名,了解一下
# 格式:(?P<別名>xxx)(?P=別名)
# 案例<html><body>hh</body></html>
print(re.match("<(?P<name1>[a-zA-Z]+)><(?P<name2>[a-zA-Z]+)>.*</(?P=name2)></(?P=name1)>", str).group())
```

## **四、高級的api:**

**findall**
```
# 查詢結果集
# findall
# 案例: 統計出python、c、c + +相應文章閱讀的次數
# 數據: "python = 9999, c = 7890, c++ = 12345"

# 返回一個列表
print(re.findall("\d+", ‘python = 9999, c = 7890, c++ = 12345‘))
```
**sub**
```
# 替換數據
# sub
# 案例: 將匹配到的閱讀次數換成998
# 數據: "python = 997"

# re.sub("替換的規則","想替換成的內容","被替換的內容")

# 只要匹配都替換
print(re.sub(‘\d+‘, ‘998‘, ‘python = 997‘))
print(re.sub(‘\d+‘, ‘998‘, ‘python = 997,c++ = 7676‘))
```
**search**
```
# 查詢結果
# search 不會從頭開始匹配,只要匹配到數據就結束
# 案例:匹配出文章閱讀的次數中的次數
# 數據:"閱讀次數為 9999"
import re

# search這個只查找一次
print(re.search(‘\d+‘, "閱讀次數為 9999").group())
print(re.search(‘\d+‘, "閱讀88次數為 9999").group())
```
**split**
```
# 字符串切割
# split
# 切割字符串“info:xiaoZhang 33 shandong”, 根據:或者空格

print(re.split(":|\s", "info:xiaoZhang 33 shandong"))
```

## **五、正則的貪婪模式與非貪婪**

在匹配符後加?
註意:python默認是貪婪的
例子:
場景[email protected] [email protected],我們想取到第一個郵箱

```
import re

# 貪婪
# 多字符之後加一個?這個非貪婪

str = "[email protected] [email protected] \[email protected]"

print(re.match(‘.+@163\.com‘, str).group())
print(re.match(‘.+?@163\.com‘, str).group())
print(re.match(‘.*?@163\.com‘, str).group())
print(re.match(‘.+?‘, str).group())
```

## **六、非[^@]**

[^字符]這個是固定的一個語法,這個意思就是非
如果寫字符串有可能會有錯,他會去匹配一個字符串出錯
例子:
場景[email protected] [email protected],我們想取到第一個郵箱
```

# [^字符]字符 非字符
import re

str = "[email protected] [email protected]"

print(re.match(‘.{4,20}@163\.com‘, str).group())

print(re.match(‘[^@]+@163\.com‘,str).group())

# 一般只填一個字符
print(re.match(‘[^bc]‘, ‘c‘).group())
```

## ****七、轉義:\\****

```
# \進行轉義
# 在正則特殊的符號, 想以字符串的形式使用使用轉義
# 匹配出163的郵箱地址,且 @ 符號之前有4到20位字符, 以.com結尾
import re

str = "[email protected]"

print(re.match(‘.{4,20}@163\.com‘, str).group())
```

## **八、r原字符使用**

```
# r原字符
import re

print("\\")
print("\\\\")

print(re.match(‘\\\\‘, ‘\\‘).group())
print(re.match(‘\\\\\\\\‘, ‘\\\\‘).group())
```

## **九、案例:**

爬取崗位職責的信息:
```
str = """
<div>
<p>崗位職責:</p>
<p>完成推薦算法、數據統計、接口、後臺等服務器端相關工作</p>
<p><br></p>
<p>必備要求:</p>
<p>良好的自我驅動力和職業素養,工作積極主動、結果導向</p>
<p>&nbsp;<br></p>
<p>技術要求:</p>
<p>1、一年以上 Python 開發經驗,掌握面向對象分析和設計,了解設計模式</p>
<p>2、掌握HTTP協議,熟悉MVC、MVVM等概念以及相關WEB開發框架</p>
<p>3、掌握關系數據庫開發設計,掌握 SQL,熟練使用 MySQL/PostgreSQL 中的一種<br></p>
<p>4、掌握NoSQL、MQ,熟練使用對應技術解決方案 </p>
<p>5、熟悉 Javascript/CSS/HTML5,JQuery、React、Vue.js</p>
<p>&nbsp;<br></p>
<p>加分項:</p>
<p>大數據,數理統計,機器學習,sklearn,高性能,大並發。</p>

</div>
"""

import re

print(re.sub(‘<.+?>|\s|&nbsp;‘, ‘‘, str))

```

完整的正則表達式知識匯總(Python知識不斷更新)