01.正则表达式

语法

  1. ==^== 破折号表示以什么为开头(破折号写在左侧)==$== 美元符号表示以什么为结尾
  2. ==.== 点号表示任意字符
  3. ==*== 星号表示前面的字符可以重复任意多遍(星号写在右侧)

例如:regex_str = "^b.*" 表示以b开头,后面出现任意字符任意多次都能匹配成功

import re

line = 'bobby123'
regex_str = "^b.*"
match_obj = re.match(regex_str, line)
if match_obj:
    print("yes")
  1. ==?== 问号表示非贪婪(问号写在右侧)

例子:我们想取boooooob这个字符串

import re

line = 'acboooooobby123'
regex_str = ".*(b.*b).*"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)
    print(result)

当我们匹配规则为

".*(b.*b).*"
# 结果为: bb

当我们匹配规则为

".*?(b.*b).*"
# 结果为: boooooobb

当我们匹配规则为

".*?(b.*?b).*"
# 结果为: boooooob

从中会发现匹配规则是从右边开始匹配的

  1. ==+== 加号表示至少出现一次

例子:我们想取boooooob这个字符串

line = 'acboooooobbby123'
regex_str = ".*?(b.+?b).*"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)
    print(result)

# 结果为:boooooob
  1. =={2} {2,} {2,5}== 大括号表示限定,限定前面字符出现的次数。两次,两次以上,两次到5次。(限定符合写在右侧)
import re

line = 'acboooooobabbaaby123'
regex_str = ".*(b.{2,}b).*"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)
    print(result)

# 结果为: baab
  1. ==|== 竖线表示或(竖线写在两个字符或字符串中间,记得要加括号)
import re

line = 'booby123'
regex_str = "(booby|booby123)"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)
    print(result)

# 结果为:booby
  1. ==[]== 中括号表示只要满足中括号内任意一个即可(字符写在括号内)
import re

line = '18699701234'
regex_str = "(1[3589][0-9]{9})"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)
    print(result)


# 结果为:18699701234

注: 中括号内的 ==^== 破折号代表非

例如:[^1] 表示非1

  1. ==\s== 反斜杠小s代表空格 ==\S== 反斜杠大S代表非空格
  2. ==\w== 反斜杠小w代表任意字符,可以用[A-Za-z0-9] ==\W== 反斜杠小W代表任意字符,表示非[A-Za-z0-9]

  3. ==[\u4E00-\u9FA5]== 表示任意中文字符

line = 'study in 南京大学'
regex_str = ".*?([\u4E00-\u9FA5]+大学)"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)

    print(result)

# 结果为:南京大学
  1. ==\d== 表示数字
import re

line = 'xxx出生于2001年'
regex_str = ".*?(\d+)年"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)

    print(result)

# 结果为:2001
  1. 综合例子
import re

line = 'xxx出生于2001年6月1日'
line = 'xxx出生于2001/7/1'
line = 'xxx出生于2001-8-1'
line = 'xxx出生于2001-09-01'
line = 'xxx出生于2001-10'
regex_str = ".*出生于(\d{4}[年/-]\d{1,2}([月/-]\d{1,2}|[月/-]$|$))"
match_obj = re.match(regex_str, line)
if match_obj:
    result = match_obj.group(1)

    print(result)