fishdm

该部分为中谷教育Python视频教程的学习笔记
正则表达式(RE)是一种小型的高度专业化的编程语言,(在Python中)它内嵌在Python中,并通过re模块实现。
其作用:
1.可以为想要匹配的相应字符串集指定规则
2.该字符串集可能包含英文语句、email地址、命令或者任何你想搞定的东西
3.可以问诸如“这个字符串匹配该模式吗?”
4“在这个字符串中是否有部分匹配该模式呢?”
5.你也可以使用RE以各种方式来修改或分割字符串
正则表达式是一门独立的语言,并不是python中特有的。正则表达式模式被编译成一系列的字节码,然后由用C编写的匹配引擎执行。
(并非所有字符串处理都能用正则表达式完成) 
字符匹配:
普通字符:
    大多数字字母和字符一般都会和自身匹配
    如正则表达式test会和字符串“test”完全匹配
元字符
    . ^ $ * + ? {} [] \ | ()

[]方括号
     常用来指定一个字符集:[abc];[a-z]
    元字符在字符集中不起作用:[akm$]
    补集匹配不在区间范围内的字符:[^5]
这是最原始的 通过普通字符去匹配它自身

>>> import re
>>> s = \'abc\'
>>> 
>>> s = r\'abc\'
>>> 
>>> re.findall(s,\'aaaaaaaaaads sscabc\')
[\'abc\']
>>> re.findall(s,\'aaaaaaaaaads sscab\')
[]
>>> re.findall(s,\'aaabcaaaabcaaads sscab\')
[\'abc\', \'abc\']
>>>

有些时候规则有些变化

>>> st = \'top tip tqp twp tep\'                #定义一个字符串
>>> 
>>> res = r\'top\'                            #定义一个正则表达式
>>> 
>>> re.findall(res,st)                #在字符串里匹配
[\'top\']
>>> res = r\'tip\'
>>> re.findall(res,st)
[\'tip\']
>>> res = r\'t[io]p\'            #如果要匹配tip和top,那么用方括号
>>> 
>>> re.findall(res,st)
[\'top\', \'tip\']
>>> res = r\'t[^io]p\'            #如果要匹配除了tip和top之外的区间,那么使用[^io]
>>> re.findall(res,st)
[\'tqp\', \'twp\', \'tep\']
>>>

 

^
    匹配行首。除非设置MULTILINE标志,它只是匹配字符串的开始。在MULTILINE模式里,它也可以直接匹配字符串中的每个换行。

>>> import re
>>> s = \'hello world,hello boy\' 
>>> r = r\'hello\'
>>> re.findall(r,s)
[\'hello\', \'hello\']
>>> r = r\'^hello\'
>>> re.findall(r,s)
[\'hello\']
>>> s = \'world,hello boy\'
>>> re.findall(r,s)
[]
>>> r = r\'^world\'
>>> re.findall(r,s)
[\'world\']
>>>

$
    匹配行尾,行尾被定义为要么是字符串尾,要么是一个换行字符后面的任何位置。

>>> s = \'world,hello boy\'
>>> r = r\'boy$\'
>>> re.findall(r,s)
[\'boy\']
>>>
综合示例:
>>> import re
>>> 
>>> r = \'t[abc$]\'
>>> 
>>> re.findall(r,\'ta\')
[\'ta\']
>>> re.findall(r,\'tb\')
[\'tb\']
>>> re.findall(r,\'tax\')
[\'ta\']
>>> re.findall(r,\'t$\')          #这里$符号作为一个普通的字符输出
[\'t$\']
>>> r = \'t[abc^]\'
 #这里^符号也是作为一个普通的字符输出。如果放在开头如\'t[^abc]\'那就是取匹配区间外的字符串了
>>> re.findall(r,\'t^\')  
[\'t^\']
>>> 
>>> r = r\'x[0123456789]x\'           #可以写成x[0-9]x
>>> 
>>> re.findall(r,\'x1x\')
[\'x1x\']
>>> re.findall(r,\'x1x,x2x\')
[\'x1x\', \'x2x\']
>>> re.findall(r,\'x1x,x2x,x9x\')
[\'x1x\', \'x2x\', \'x9x\']
>>> r = r\'x[0-9]x\'
>>> re.findall(r,\'x1x,x2x,x9x\')
[\'x1x\', \'x2x\', \'x9x\']
>>> r = r\'x[a-zA-Z0-9]x\'        #同理,匹配一个比较大的范围,用-号
>>> re.findall(r,\'x1x,xRx,xgx\')
[\'x1x\', \'xRx\', \'xgx\']
>>>

分类:

技术点:

相关文章:

  • 2021-08-11
  • 2022-02-11
  • 2021-08-26
  • 2021-05-09
  • 2022-01-05
猜你喜欢
  • 2022-12-23
  • 2021-10-13
  • 2021-09-11
相关资源
相似解决方案