NEW learning : Regular Expression

发布时间 2023-08-14 13:28:56作者: prayerto

STEP 1 : The primary formula in the RE code base :

    

result =re.match(pattern, str)
#pattern 为要校验的规则
#str 为要进行校验的字符串
>>> import re
>>> print(re.match('www', 'www.runoob.com').span()) #在起始位置匹配
(0, 3)
>>> print(re.match('com', 'www.runoob.com')) #不在起始位置匹配
None
#如果result不为None,则group方法则对result进行数据提取

字符 功能
. 匹配任意1个字符(除了\n)
[] 匹配[]中列举的字符
\d 匹配数字,也就是0-9
\D 匹配非数字,也就是匹配不是数字的字符
\s 匹配空白符,也就是 空格\tab
\S 匹配非空白符,\s取反
\w 匹配单词字符, a-z, A-Z, 0-9, _
\W 匹配非单词字符, \w取反

#首先清楚手机号的规则
#1.都是数字 2.长度为11 3.第一位是1 4.第二位是35678中的一位
>>> import re
>>> pattern ="1[35678]\d{9}"
>>> phoneStr ="18230092223"
>>> result =re.match(pattern,phoneStr)
>>> result.group()
'18230092223'

字符 功能
^ 匹配字符串开头 该字符串如^/d/d/d 必须以数字开头
$ 匹配字符串结尾
\b 匹配一个单词的边界
\B 匹配非单词边界

#定义规则匹配str="ho ve r"
#1. 以字母开始 ^\w
#2. 中间有空字符 \s
#3. \b的两种解释是:
#'\b', 如果前面不加r, 那么解释器认为是转义字符“退格键backspace”;
#r'\b', 如果前面加r, 那么解释器不会进行转义,\b 解释为正则表达式模式中的字符串边界。
#4. ve两边分别限定匹配单词边界
>>> import re
>>> str ="dasdho ve rgsdf"
>>> pattern =r"^\w+\s\bve\b\sr"
>>> result =re.match(pattern, str)
>>> result.group()
'dasdho ve r'

字符 功能
| 匹配左右任意一个表达式
(ab) 将括号中字符作为一个分组
\num 引用分组num匹配到的字符串
(?P<name>) 分组起别名
(?P=name) 引用别名为name分组匹配到的字符串

#匹配出0-100之间的数字
#首先:正则是从左往又开始匹配
#经过分析: 可以将0-100分为三部分
#1. 0 "0$"
#2. 100 "100$"
#3. 1-99 "[1-9]\d{0,1}$"
#所以整合如下
>>> import re
>>> pattern =r"0$|100$|[1-9]\d{0,1}$"
>>> result = re.match(pattern,"27")
>>> result.group()
'27'
>>> result =re.match(pattern,"212")
>>> result.group()
Traceback (most recent call last):
File "<stdin>", line 1, in<module>
AttributeError: 'NoneType'object has no attribute 'group'
#将0考虑到1-99上,上述pattern还可以简写为:pattern=r"100$|[1-9]?\d{0,1}$"

#(?<=abc)def ,并不是从 a 开始搜索,而是从 d 往回看的。你可能更加愿意使用 search() 函数,而不是 match() 函数:
>>> import re
>>> m =re.search('(?<=abc)def', 'abcdef')
>>> m.group(0)
'def'
#搜索一个跟随在连字符后的单词
>>> m =re.search(r'(?<=-)\w+', 'spam-egg')
>>> m.group(0)
'egg'

>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']
>>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
['0', '3', '9']