大家好,我是 星源,19岁自学Python的编程小白 🤓。 今天开始探索正则表达式的魔法!它是文本处理的瑞士军刀,帮我们精准匹配和操作字符串,效率翻倍!✨


📌 今日学习内容

👉 “用正则表达式解锁文本匹配的终极技巧,从简单搜索到复杂替换一网打尽!”


✨ 知识点讲解

1️⃣ 正则表达式基础

  • 概念:正则表达式(regex)是文本模式的描述规则,用来匹配符合特定规则的字符串。

  • 引入模块import re

2️⃣ 匹配文本模式

  • 编译正则对象re.compile()

  • 示例

    >>> import re
    >>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
    >>> mo = phoneNumRegex.search('My number is 415-555-4242.')
    >>> mo.group()
    '415-555-4242'

3️⃣ 分组

  • 分组语法:用括号 () 分组。

  • 示例

    >>> phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
    >>> mo = phoneNumRegex.search('My number is 415-555-4242.')
    >>> mo.group(1)
    '415'
    >>> mo.groups()
    ('415', '555', '4242')

4️⃣ 匹配多次

  • 量词

    • *:匹配0次或多次。

    • +:匹配1次或多次。

    • ?:匹配0次或1次。

  • 示例

    >>> batRegex = re.compile(r'Bat(wo)?man')
    >>> mo1 = batRegex.search('The Adventures of Batman')
    >>> mo1.group()
    'Batman'
    >>> mo2 = batRegex.search('The Adventures of Batwoman')
    >>> mo2.group()
    'Batwoman'

5️⃣ 贪婪与非贪婪匹配

  • 贪婪匹配:匹配最长可能的字符串。

  • 非贪婪匹配:匹配最短可能的字符串,加 ?

  • 示例

    >>> greedyRegex = re.compile(r'<.*>')
    >>> mo = greedyRegex.search('<To serve man> for dinner.>')
    >>> mo.group()
    '<To serve man> for dinner.>'
    ​
    >>> nongreedyRegex = re.compile(r'<.*?>')
    >>> mo = nongreedyRegex.search('<To serve man> for dinner.>')
    >>> mo.group()
    '<To serve man>'

6️⃣ findall() 方法

  • 功能:返回所有匹配的子串列表。

  • 示例

    >>> phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
    >>> phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
    ['415-555-9999', '212-555-0000']

7️⃣ 字符分类

  • 常见分类

    • \d:数字(0–9)。

    • \w:字母、数字或下划线。

    • \s:空白字符(空格、制表符、换行)。

  • 示例

    >>> xmasRegex = re.compile(r'\d+\s\w+')
    >>> xmasRegex.findall('12 drummers, 11 pipers, 10 lords, 9 ladies')
    ['12 drummers', '11 pipers', '10 lords', '9 ladies']

8️⃣ 通配符与转义字符

  • 通配符. 匹配任意字符(换行除外)。

  • 转义字符:用 \ 匹配特殊字符。

  • 示例

    >>> regex = re.compile(r'.at')
    >>> regex.findall('The cat in the hat sat on the flat mat.')
    ['cat', 'hat', 'sat', 'lat', 'mat']

✅ 总结

  1. 正则表达式通过 re.compile() 编译,用 search()findall() 操作字符串。

  2. 分组用括号 (),量词 *+? 控制匹配次数。

  3. 贪婪匹配默认,非贪婪加 ?

  4. \d\w\s 等分类字符简化模式编写。

  5. . 作通配符,\ 用于转义。


📢 互动提问

👉 “第一次写正则时,有没有被 .* 的贪婪匹配坑过,结果匹配了超长字符串?” 留言分享你的“匹配灾难”,一起互相慰藉! 😄

希望今天的正则之旅让你兴奋又充实,文本处理的神器现在已经握在你手里啦!下节课我们继续深挖更多实战技巧,拜拜!👋

更多推荐