python 正则规则

正则表达式是Python程序设计中非常实用的功能,本文就常用的正则表达式做一汇总,供大家参考之用。具体如下:

1.re 模块:核心函数和方法:
(1)re.compile()
(2)re.findall()
(3)re.match()
(4)re.search()
(5)re.split()
(6)re.sub()和re.subn()

'''
    正则表达式
    常见的特殊符号
    . 匹配任何字符,换行符除外
    ^ 匹配字符串的开始
    $ 匹配字符串的结尾
    * 匹配前面出现的正则符号零次或者多次
    + 匹配前面出现的正则符号的一次或者多次
    ? 匹配前面出现的正则表达式零次或者一次
    {N} 匹配前面出现的正则表达式N次
    {M,N} 匹配前面出现的正则表达式M次到N次
    [x-y] 匹配从x到y中的任意一个字符

    常见的特殊字符
    \d  匹配任何数字[0-9]
    \D  匹配非数字字符
    \w  匹配字母,数字,下划线
    \W  匹配不是字母,数字,下划线
    \s  匹配空白字符串
    \S  匹配不是空白的字符
    \b  匹配单词的开始和结束
    \B  匹配不是单词开始和结束的位置
'''


#匹配邮箱 不能匹配后面的.cn,找方法解决
import re
str = r"^[^_]\w+@\w+\.\w{1,5}"
re_str = re.compile(str)
test_str = 'lck@126.com.cn'
print re.findall(str,test_str)
print re_str.findall(test_str)
#匹配电话号码(还是有问题的)

str = r"\+?[8,6,-]*1\d{10}$"
test_str = '+86-17098765679'
test_str2 = '1908767890'
print re.findall(str,test_str)
print re.findall(str,test_str2)

#匹配单词边界
str = r"\bthe"
str2 = r"\Bthe"
test_str = 'the boy is a good child'
test_str2 = "the boy is the woman's son"
print re.findall(str, test_str)
print re.findall(str2, test_str)
print re.findall(str, test_str)
print re.findall(str2,test_str2)


#分组
str = r"(abc)"
re_str = re.compile(str)
test_str = 'abcabccabcdabc'
print re_str.findall(test_str)
m = re_str.findall(test_str)
# print m.group()
# print m.groups()

#贪婪模式  非贪婪模式  ?非贪婪模式
str = r"abc"
str2 = r"abc{1,3}"
str3 = r"abc*?"
str4 = r"abc{1,3}?"
print re.findall(str,test_str)
print re.findall(str2,test_str)
print re.findall(str3,test_str)
print re.findall(str4,test_str)

#match 方法
print re.match(str,test_str)
print re.match(str,test_str).group()
print re.match(r"sdc", test_str)

#search 方法
print re.search(str,test_str)
print re.match(str,test_str).group()
print re.search(r"dasf",test_str)

#split 方法
print re.split(str,test_str,maxsplit=2)

#sub he subn方法
print re.sub(str, 'cba', test_str)

#62 151  212
#6   7   2
输出如下:

/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/study-software/zhihuSpider/python_test/cookbook_2.py
['lck@126.com']
['lck@126.com']
['+86-17098765679']
[]
['the']
[]
['the']
[]
['abc', 'abc', 'abc', 'abc']
['abc', 'abc', 'abc', 'abc']
['abc', 'abcc', 'abc', 'abc']
['ab', 'ab', 'ab', 'ab']
['abc', 'abc', 'abc', 'abc']
<_sre.SRE_Match object at 0x104a78e00>
abc
None
<_sre.SRE_Match object at 0x104a78e00>
abc
None
['', '', 'cabcdabc']
cbacbaccbadcba


Process finished with exit code 0

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值