正则表达式
发布时间:2020-12-13 21:54:22 所属栏目:百科 来源:网络整理
导读:文章作者:Tyan 博客:noahsnail.com | CSDN | 简书 1. 正则表达式 正则表达式(Regular Expression)描述了一种字符串匹配模式,主要用来检索、替换匹配某种模式的字符串。 2. 正则表达式语法 下面以Python代码来展示正则表达式的匹配。 . . 可以匹配任意单个
文章作者:Tyan 1. 正则表达式正则表达式(Regular Expression)描述了一种字符串匹配模式,主要用来检索、替换匹配某种模式的字符串。 2. 正则表达式语法下面以Python代码来展示正则表达式的匹配。
import re
print(re.findall(r'.','abc'))
# 代码执行结果
['a','b','c']
import re
print(re.findall(r'^Th','This is a demo. This is a demo.'))
# 代码执行结果
['Th']
import re
print(re.findall(r'demo$','This is a demo. This is a demo'))
# 代码执行结果
['demo']
import re
print(re.findall(r'test*','t te tes test testt'))
# 代码执行结果
['tes','test','testt']
import re
print(re.findall(r'test+','t te tes test testt'))
# 代码执行结果
['test','testt']
import re
print(re.findall(r'test?','test']
import re
print(re.findall(r'test?','t te tes test? testt'))
# 代码执行结果
['test?']
import re
print(re.findall(r'te|st','t te tes test'))
# 代码执行结果
['te','te','st']
import re
print(re.findall(r'[test]','This is a test'))
# 代码执行结果
['s','s','t','e','t']
import re
print(re.findall(r'[^test]','This is a test'))
# 代码执行结果
['T','h','i',' ','a',' ']
import re
print(re.findall(r'test{1,2}','This is a test testt'))
# 代码执行结果
['test','testt']
import re
print(re.findall(r'(test){1,'test']
import re
print(re.findall(r'w','Is this a test?_'))
# 代码执行结果
['I','t']
import re
print(re.findall(r'W','Is this a test?'))
# 代码执行结果
[' ','?']
import re
print(re.findall(r'd','test 123'))
# 代码执行结果
['1','2','3']
import re
print(re.findall(r'D','test 123'))
# 代码执行结果
['t',' ']
import re
print(re.findall(r's','test 123n'))
# 代码执行结果
[' ','n']
import re
print(re.findall(r'S','test 123n'))
# 代码执行结果
['t','1','3']
import re
print(re.findall(r'n','test 123n'))
# 代码执行结果
['n']
import re
print(re.findall(r'f','test 123f'))
# 代码执行结果
['x0c']
import re
print(re.findall(r'r','test 123r'))
# 代码执行结果
['r']
import re
print(re.findall(r't','test 123t'))
# 代码执行结果
['t']
import re
print(re.findall(r'v','test 123v'))
# 代码执行结果
['x0b']
import re
print(re.findall(r'Th(?=is)','There or This or The?'))
# 代码执行结果,匹配的是This中的Th
['Th']
import re
print(re.findall(r'Th(?!is)','There or This or The?'))
# 代码执行结果,匹配的是There,The中的Th
['Th','Th']
import re
print(re.findall(r'(?<=H)e','The or He or She?'))
# 代码执行结果,匹配的是He中的e
['e']
import re
print(re.findall(r'(?<!H)e','The or He or She?'))
# 代码执行结果,匹配的是The,She中的e
['e','e']
参考资料
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |