Python 正则与url匹配

详细用法可参考:https://blog.csdn.net/weixin_40907382/article/details/79654372

Django 1.9 前 url匹配方法可以同时匹配正则和字符串,但是1.9之后被划分为了两个方法。

首先我们回顾一下python正则:

正则(re):是一种高级的字符串处理方式,主要用于字符串的匹配。

字符匹配被分为了两种:

内容匹配:通过描述内容的类型和长度来进行匹配的,匹配的精度比较高,比较繁琐

匹配手机号:匹配一个139开头的后面是8位数字的字符串

Re

findall方法:在指定的字符串当做匹配所有满足条件的字符。

内容的类型:

原样匹配 通常用于和其他匹配结合

import re

re.match #从开始位置开始匹配,如果开头没有则无

re.search #搜索整个字符串

re.findall #搜索整个字符串,返回一个list
import re
a='hello world I am your friend I am 18_1 years old aheheha 333 4423'
result = re.findall(r'h',a)
print(result)    #['h', 'h', 'h', 'h']
result = re.match(r'h',a).
print(result)    #<_sre.SRE_Match object; span=(0, 1), match='h'>
result = re.match(r'h',a).group()
print(result)    # h
result = re.search(r'h',a)
print(result)    #<_sre.SRE_Match object; span=(0, 1), match='h'>
result = re.search(r'h',a).group()
print(result)    # h

. 匹配任意非换行字符

a='hello world I am your friend I am 18_1 years old aheheha 333 4423'
result = re.findall(r'.',a)
print(result)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'I', ' ', 'a', 'm', ' ', 'y', 'o', 'u', 'r', ' ', 'f', 'r', 'i', 'e', 'n', 'd', ' ', 'I', ' ', 'a', 'm', ' ', '1', '8', '_', '1', ' ', 'y', 'e', 'a', 'r', 's', ' ', 'o', 'l', 'd', ' ', 'a', 'h', 'e', 'h', 'e', 'h', 'a', ' ', '3', '3', '3', ' ', '4', '4', '2', '3']

\d 匹配所有的数字

a='hello world I am your friend I am 18_1 years old aheheha 333 4423'
result = re.findall(r'\d',a)
print(result)
['1', '8', '1', '3', '3', '3', '4', '4', '2', '3']

\D 匹配所有非数字

a='hello world I am your friend I am 18_1 years old aheheha 333 4423'
result = re.findall(r'\D',a)
print(result)
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', 'I', ' ', 'a', 'm', ' ', 'y', 'o', 'u', 'r', ' ', 'f', 'r', 'i', 'e', 'n', 'd', ' ', 'I', ' ', 'a', 'm', ' ', '_', ' ', 'y', 'e', 'a', 'r', 's', ' ', 'o', 'l', 'd', ' ', 'a', 'h', 'e', 'h', 'e', 'h', 'a', ' ', ' ']

\s 匹配所有的空格

/S匹配所有非空格

 

 

 

 

 

 

 

 

 

 

 

 

 

 

正则的方法

Findall 匹配所有的可能性

Search 从字符串当中匹配一次复合条件的字符,匹配到以组的格式返回

Match 从字符串开头匹配一次复合条件的字符,匹配到以组的格式返回

Split 切分,重构字符串的split方法

贪婪和反贪婪

 

 

 

 

 

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值