Python之正则表达式的使用

########正则表达式########

 

 

 

## 通配符的使用

 

在python中的正则表达式里对通配符的使用也相当规范

例如:*  ?  .    [0-9]  [a-z]  [A-Z]等;而不同于shell里,如[[:digit:]] [[:alpha:]]等不能识别

 

# glob.glob: 返回所有匹配正则的路径(返回的是一个列表)

# glob.iglob: 返回所有匹配正则的路径(返回的是一个生成器)

import glob

print(glob.glob('/etc/*.conf'))
print(glob.glob('/etc/????.conf', recursive=True))
print(glob.glob('/etc/*[0-9A-Z]*.conf'))

print(glob.iglob('/etc/*[0-9A-Z]*.conf'))
print(type(glob.iglob('/etc/*[0-9A-Z]*.conf')))
print(next(glob.iglob('/etc/*[0-9A-Z]*.conf')))

 

 

 

## 正则表达式常用逻辑及方法

 

import re

s = "home/kiosk/Desktop/python/python/python3.6"

# findall方法
# 编写正则规则
pattern1 = r'home'
pattern2 = r'python'
print(re.findall(pattern1, s))
print(re.findall(pattern2, s))
# 可见findall方法是找出全部匹配规则的字符

# match方法
print(re.match(pattern2, s))
obj = re.match(pattern1, s)
print(obj.group())
# 可见match方法是匹配第一个字符,若没有匹配成功返回值未None,匹配成功调用group方法打印匹配的值

# search方法
obj1 = re.search(pattern1, s)
obj2 = re.search(pattern2, s)
print(obj1.group())
print(obj2.group())
# 可见search方法挥扫描整个字符串但值返回第一个匹配成功的内容

 

 

 

## 正则表达式特殊字符类

 

字符类:
    [pP]ython
    westos[pP]
    [aeiou]
    [a-z]
    [A-Z]
    [a-zA-Z0-9]
    [^0-9]

特殊字符类:
    . : 匹配除了\n之外的任意字符; [.\n]
    \d :  digit--(数字), 匹配一个数字字符, 等价于[0-9]
    \D : 匹配一个非数字字符, 等价于[^0-9]
    \s :  space(广义的空格: 空格, \t, \n, \r), 匹配单个任何的空白字符;
    \S :  匹配除了单个任何的空白字符;
    \w :  字母数字或者下划线, [a-zA-Z0-9_]
    \W : 除了字母数字或者下划线, [^a-zA-Z0-9_]

import re

print(re.findall(r'[^0-9]','houzeyu123321houzeyu\n\n\n\n\n'))
print(re.findall(r'[0-9]','houzeyu123321houzeyu\n\n\n\n\n'))
print(re.findall(r'\d','houzeyu123321houzeyu\n\n\n\n\n'))
print(re.findall(r'\D','houzeyu123321houzeyu\n\n\n\n\n'))
print(re.findall(r'.','houzeyu123321houzeyu\n\n\n\n\n'))

 

print(re.findall(r'\s', '\n当前\r文章阅\t读量为8'))
print(re.findall(r'\S', '\n当前\r文章阅\t读量为8'))

print(re.findall(r'\w', '12当前python文章阅_读量为8&%#'))
print(re.findall(r'\W', '12当前python文章阅_读量为8&%#'))

 

 

 

## 指定字符出现的次数

 

匹配字符出现次数:
    *  : 代表前一个字符出现0次或者无限次;    d*,  .*
    + : 代表前一个字符出现一次或者无限次;     d+
    ? : 代表前一个字符出现1次或者0次;   假设某些字符可省略, 也可以不省略的时候使用

第二种方式:
    {m}: 前一个字符出现m次;
    {m,}: 前一个字符至少出现m次;  * == {0,}; + ==={1,}
    {m,n}: 前一个字符出现m次到n次; ? === {0,1}

import re

print(re.findall(r'd*', ''))
print(re.findall(r'd*', 'ddd'))
print(re.findall(r'd*', 'dwww'))
print(re.findall(r'.*', 'linux'))

print(re.findall(r'd+', ''))
print(re.findall(r'd+', 'ddd'))
print(re.findall(r'd+', 'dwww'))
print(re.findall(r'd+', 'linux'))

pattern = r'\d{3}[\s-]?\d{4}[\s-]?\d{4}'
print(re.findall(pattern,'188 6754 7645'))
print(re.findall(pattern,'18867547645'))
print(re.findall(pattern,'188-6754-7645'))

 

 

 

 

 

##############待续##############

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值