本文由我司收集整编,推荐下载,如有疑问,请与我司联系
Python
正则表达式练习
#re
正则表达式
import
re#1
通配符(
.
可匹配出换行符外的任意一个字符
.ython--
qython
+ython
)
#2\
特殊字符进行转义
Python\\
或使用原始字符
r’Python\’#3[]
字符集
[pg]ython--
匹配
python
、
gython [a-z]
匹配
a
到
z
任意一个字符
[a-zA-Z0-9]
匹配任意
一个大小写字母和数字
#4
|
选择符
管道
|
python|jython--
匹配字符串
python
和
jython#5
()子模式:只选择模式的一部分()
p
(
ython|json
)
--
匹配
python pjson
单个字符
#6?
可选项:在子模式后加?变成可选项
”““r’()?(www\.)?python\’==
可能
匹配的字符串:
pythonpythonpythonpython”“““““(param)*:
允许模式重复
0
次或多次
(param)+:
允许模式重复
1
次或多次
(param){m,n}:
允许模式重复
m-n
次
r’w*\.python\’==
匹配到
’python’
也会匹配
’.python’
,也会匹
配
’wwwwwpython’llo.....test.head.falj.kfal’print(re.split(‘[.]+’,txt))print(re.split(‘[.]’,txt))”
““C:\python3.7\python.exe
D:/Python-Test/qiubai/qiubai/Test9.pyNone
_sre.SRE_Match
object; span=(0, 1), match=‘p’ [‘He’, ‘hello’, ‘test’, ‘head’, ‘falj’, ‘kfal’][‘He’, ‘hello’, ‘‘,
‘‘,
‘‘,
‘‘,
‘test’,
‘head’,
‘falj’,
‘kfal’]”““#10
最多可以分割的部分数
txt
=
‘He.hello.....test.head.falj.kfal’print(re.split(‘[.]+’,txt,maxsplit=2))print(re.split(‘[.]+’,txt,m
axsplit=1))”““C:\python3.7\python.exe
D:/Python-Test/qiubai/qiubai/Test9.py[‘He’,
‘hello’,
‘test.head.falj.kfal’][‘He’,
‘hello.....test.head.falj.kfal’]”““#11
在字符串中查找所
有单词
findall
以列表的形式返回
p
=
‘[a-zA-Z]+’word
=
“hello,world,I,am
you
--
hefajlka?”print(“
查找单词:
”,re.findall(p,word))q
=
r’[-?]’print(“
查找标点符
号
”,re.findall(q,word))”““C:\python3.7\python.exe
D:/Python-Test/qiubai/qiubai/Test9.py
查找单词:
[‘hello’,
‘world’,
‘I’,
‘am’,
‘you’,
‘hefajlka’]
查找标点符号
[‘-’,
‘-’,
‘?’]”““#12
sub
替换
pat
=
‘{name}’txt
=
“Hello
{name}”print(re.sub(pat,’
张
三
’,txt))”““C:\python3.7\python.exe
D:/Python-Test/qiubai/qiubai/Test9.pyHello
张
三
”““#13
匹配对象和组
’There
(was
a(wee)
(cooper))
who
(lived
in
fyfe)’”““
组
0
--
There was a wee cooper who lived in fyfe
组
1 -- was a wee cooper
组
2 -- wee
组
3 --
cooper
组
4
--
lived
in
fyfe”“““r’www\.(.+)\$==
组
0
包含整个字符串
组
1
包含位于