首页 > 其他 > 详细

正则表达式

时间:2021-04-20 20:50:05      阅读:19      评论:0      收藏:0      [点我收藏+]

 

一、验证匹配

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/p/14682568.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!