什么是正则表达式?

什么是正则表达式?

正则表达式是一种用来描述字符串的规则。就像数学中的公式一样,用于查找、替换、删除等操作。在不同编程语言中,正则表达式的写法和功能可能会稍有区别,但基本思路是相似的。

基本语法

匹配单个字符

. 表示匹配除换行符之外的任意字符。

import re
pattern = r"h.t"
string = "hello world"
match = re.search(pattern, string)
if match:
    print(match.group())    # hlt

匹配任意多个字符

* 表示匹配前面字符任意个数。
+ 表示匹配前面字符至少一个。
? 表示匹配前面字符零个或一个。

import re
pattern1 = r"he.*"
pattern2 = r"he.+"
pattern3 = r"he?"
string = "hello world"
match1 = re.search(pattern1, string)
match2 = re.search(pattern2, string)
match3 = re.search(pattern3, string)
if match1:
    print(match1.group())    # hello world
if match2:
    print(match2.group())    # hello world
if match3:
    print(match3.group())    # he

匹配固定数量的字符

{n} 表示匹配前面的字符恰好 n 次。
{n,} 表示匹配前面的字符至少 n 次。
{n,m} 表示匹配前面的字符至少 n 次,不超过 m 次。

import re
pattern1 = r"a{2}"
pattern2 = r"a{2,}"
pattern3 = r"a{1,3}"
string = "aabbcaaaa"
match1 = re.search(pattern1, string)
match2 = re.search(pattern2, string)
match3 = re.search(pattern3, string)
if match1:
    print(match1.group())    # aa
if match2:
    print(match2.group())    # aaaa
if match3:
    print(match3.group())    # aaa

匹配特定字符集合

[ ] 表示匹配方括号中的任意一个字符,也可以用 - 表示字符的范围。
[^ ] 表示匹配除方括号中的字符之外的任意一个字符。

import re
pattern1 = r"[aeiou]"
pattern2 = r"[a-z]"
pattern3 = r"[^h]"
string = "hello world"
matches1 = re.findall(pattern1, string)
matches2 = re.findall(pattern2, string)
matches3 = re.findall(pattern3, string)
print(matches1)    # ['e', 'o', 'o']
print(matches2)    # ['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']
print(matches3)    # ['e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

匹配位置

^ 在正则表达式开头表示匹配字符串的开始位置。
$ 在正则表达式末尾表示匹配字符串的结束位置。
\b 表示匹配单词边界。
\B 表示匹配非单词边界。

import re
pattern1 = r"^h"
pattern2 = r"d$"
pattern3 = r"\bworld\b"
pattern4 = r"\Bll\B"
string = "hello world"
match1 = re.search(pattern1, string)
match2 = re.search(pattern2, string)
match3 = re.search(pattern3, string)
match4 = re.search(pattern4, string)
if match1:
    print(match1.group())    # h
if match2:
    print(match2.group())    # d
if match3:
    print(match3.group())    # world
if match4:
    print(match4.group())    # ll

使用括号括号可以将几个字符视为一个整体,从而进行更加复杂的匹配。

import re
pattern1 = r"(he)+"
pattern2 = r"(\d{3})-\d{4}-\d{4}"
string1 = "hello world"
string2 = "021-1234-5678"
match1 = re.search(pattern1, string1)
match2 = re.search(pattern2, string2)
if match1:
    print(match1.group())    # he
if match2:
    print(match2.group(1))    # 021

实战应用

验证手机号码

import re
def is_phone_number(number):
    pattern = r"^1[356789]\d{9}$"
    match = re.search(pattern, number)
    if match:
        return True
    else:
        return False

print(is_phone_number("13812345678"))    # True
print(is_phone_number("10086"))    # False

提取网页中的图片链接

import re
import requests
from bs4 import BeautifulSoup

url = "https://www.baidu.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for img in soup.find_all("img"):
    src = img.get("src")
    if src:
        pattern = r"https?://.+?\.(jpg|png|gif)"
        match = re.search(pattern, src)
        if match:
            print(match.group())

字符串替换

import re
string = "hello world"
pattern = r"o"
new_string = re.sub(pattern, "0", string)
print(new_string)    # hell0 w0rld

结论

正则表达式是一种强大的规则,应用范围非常广泛。虽然看起来有些晦涩,但只要熟练掌握基础语法,就可以运用自如,威力无穷。学习有效的正则表达式写法,对于提高编程效率有巨大帮助。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程