正则表达式

一、验证匹配

import re
#一、判断字符串是否匹配
#re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;
# 而re.search匹配整个字符串,直到找到一个匹配。
# 1、 re.match
test='welcome to wonderland'
if re.match(r'welcome to wonderland',test):
    print('right')
else:
    print('failed')

#2、  re.search
test='welcome to wonderland'
if re.search(r'wonderland',test):
    print('right')
else:
    print('failed')

#二、切分字符串
#1、 split无法识别连续的空格
one='a b   c'.split(' ')
print(one)
#结果输出
#['a', 'b', '', '', 'c']

#2、 使用正则
two=re.split(r's+','a b   c')
print(two)
#结果输出
#['a', 'b', 'c']

#加入逗号,
three= re.split(r'[s\,]+', 'a,b, c  d')
print(three)
#结果输出
#['a', 'b', 'c', 'd']

#加入分号;
four=re.split(r'[s\,;]+', 'a,b;; c  d')
print(four)
#结果输出
#['a', 'b', 'c', 'd']

  

声明 欢迎转载,但请保留文章原始出处:) 博客园:https://www.cnblogs.com/chenxiaomeng/ 如出现转载未声明 将追究法律责任~谢谢合作
原文地址:https://www.cnblogs.com/chenxiaomeng/p/14682568.html