基本正则表达式笔记
正则表达式
用一些特定的字符串来匹配目标字符串里面的内容
笔记
import re
# 单个字符的匹配
# [] \d \w \s
# . 匹配单个字符:['Good', 'food']
print(re.findall(".ood","I say Good and food"))
# [] 括号里面 的内容会被逐一的单个匹配 ['Good', 'food']
print(re.findall("[Gf]ood","I say Good and food"))
# \d 匹配单个数字 ['4', '0']
print(re.findall("\d","I am 40"))
# 多个\d 就可以匹配多个 单个数字 并组合起来 ['40']
print(re.findall("\d\d","I am 400"))
# \w 匹配0~9 a~z A~Z 的内容 ['a', 'b', '1', '_', 's', 'k', 'y', 's', 's', 's']
print(re.findall("\w","ab!1_+sky+s ss"))
# \s 匹配空字符 [' ', ' ', ' ', ' ']
print(re.findall("\s","ab!1_+s ky+s ss"))
# 一组字符的匹配
# 直接匹配 ['Good']
print(re.findall("Good","I say Good"))
# 分隔符 匹配两个不同的字样 ['Good', 'food']
print(re.findall("Good|food","I say Good and food"))
# * 用来匹配字符串出现0次或者多次 ['google', 'ggle', 'goooogle']
print(re.findall("go*gle","I like google not ggle goooogle and gsosgle"))
# + 用来匹配字符串出现1次或者多次 ['google', 'goooogle']
print(re.findall("go+gle","I like google not ggle goooogle and gsosgle"))
# ? 用来匹配左邻字符出现0次或者1次的字符串 ['ggle']
print(re.findall("go?gle","I like google not ggle goooogle and gsosgle"))
# {} 用来指定左邻字符匹配的个数 ['google']
print(re.findall("go{2}gle","I like google not ggle goooogle and gsosgle"))
# ['google', 'goooogle']
print(re.findall("go{2,10}gle","I like google not ggle goooogle and gsosgle"))
# ^用来判断字符串的开头是不是右邻字符串 ['I like'],不是则返回空
print(re.findall("^I like","I like google not ggle goooogle and gsosgle"))
# []
print(re.findall("^google","I like google not ggle goooogle and gsosgle"))
# $ 用来判断字符串的结尾是不是左邻字符串 ['gsosgle'],不是则返回空
print(re.findall("gsosgle$","I like google not ggle goooogle and gsosgle"))
#['allen', 'allen']
print(re.findall("allen","my name is allenallen"))
# ()\\ 用来匹配所匹配的字符串是哪个分组
test=re.search("(allen)\\1","my name is allenallen")
# allenallen
print(test.group())
#<re.Match object; span=(11, 21), match='allenallen'>
print(test)
#['allen']
print(re.findall("(allen)\\1","my name is allenallen"))
本文来自博客园,作者:{Zeker62},转载请注明原文链接:https://www.cnblogs.com/Zeker62/p/15167803.html