python正则表达式练习_【IT专家】Python正则表达式练习

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

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

包含位于

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值