- 分割字符串
使用re.split(pattern,string),通过正则表达式可以指定多个分隔符,如果正则包含了了括号捕获分组,分隔符也会出现在结果中,re.split也可以用来重新构造新字符串
import re
line='abd abs;asd ass,g g'
res1=re.split(r'[;,\s]\s*',line)
fileds=re.split(r'(\s|;|,)',line)
value=fileds[::2]
tag=fileds[1::2]
#重新构造字符串
new_line=''.join(v+d for v,d in zip(value,tag))
print(res1)
print(new_line)
-
字符串开头或者结尾匹配
str.startswith()
str.endswith()
str[start:final:step] -
shell部分回去实验
-
字符串匹配、搜索、替换
搜索:str.find()以及第2条前两个方法
匹配:pattern.match(str)、pattern.findall(str)
pattern想要多次复用就可以采用pattern=re.compile(r’正则’)
这一点和js的区别是js是str.match(pattern)而python是pattern.match(str),而且js的正则需要注意转义的问题,python只需要r’(\d+)(\d+)’,当然也可以像js那样用反斜杠/*
替换:str.replace(oldstr,newstr)这一点和js的区别是js支持正则,python的replace不支持
re.sub()非常好用
多行匹配:*’.’**不能匹配换行符,因此可以将换行符加入到模式中
comp='/*注释' \
'fff*/'
comment=re.compile(r'/\*((?:.|\n)*?)\*/')
print(comment.findall(comp))
-
删除字符串中开头结尾或者中间不想要的字符str.strip()
application审查清理文本字符串: -
处理html和xml, html和xml包
处理<: html.escape(str)