正则表达式re

 

  • ^.*$?
# 正则表达式:^.*$?
# re.match
import re
line = "bobby123"
regex_str = "^b.*"
# ^ 以特殊开头, . 任意字符, * 前边的字符可以重复任意遍。也就是b可以重复任意次
if re.match(regex_str, line):
    print("yes")

# $ 以特殊字符结尾的
regex_str2 = "^b.*3$"
if re.match(regex_str2, line):
    print("yes")


# ? 非贪婪匹配
# booob 和 bb 都可以,从左边开始匹配,遇到第一个就返回
line2 = "booobby123b"
regex_str3 = ".*?(b.*?b).*"
match_obj = re.match(regex_str3, line2)
if match_obj:
    print(match_obj.group(1))
  • ()+{}
import re
line = "baabbooooby123"
regex_str1 = ".*(b.+b).*"
regex_str2 = ".*(b.{3,6}b).*"  # 至少三次,至多6次
regex_str3 = ".*(b.{2}b).*"    # 可以指定出现次数

# 前面可以是任意字符,后面可以是任意字符,匹配出以b开头,以b结尾,中间是任意字符至少要出现一次
match_obj = re.match(regex_str2, line)
if match_obj:
    print(match_obj.group(1))
  • | []
import re
line = "bobby123"
regex_str = "((bobby|b1234)123)"
# | 表示或
# 套娃,加括号,提取子字符串
match_obj = re.match(regex_str, line)
if match_obj:
    print(match_obj.group(1))

line2 = "bobby123china"
regex_str2 = ".*([abcde]hina)"
# [] 可以是中括号当中的任意一个
match_obj = re.match(regex_str2, line2)
if match_obj:
    print(match_obj.group(1))

line3 = "13886624992"
regex_str3 = "(1[324][0-9]{9})"
# [0-9]{9} ,0-9当中的任意一个数,可以出现九次
# [^1]{9}, 不等于1,出现九次
match_obj = re.match(regex_str3, line3)
if match_obj:
    print(match_obj.group(1))
  • \s \S \w \W
# 正则表达式:\s \S \w \W
import re
line = "您 好"
regex_str = "(您\s好)"
# \s 匹配空格
match_obj = re.match(regex_str, line)
if match_obj:
    print(match_obj.group(1))

line2 = "您good好"
regex_str2 = "(您\S+好)"
# \s 匹配非空格,不能出现空格
match_obj = re.match(regex_str2, line2)
if match_obj:
    print(match_obj.group(1))

line3 = "您s好"
regex_str3 = "(您[\w]好)"
# regex_str3 = "(您[A-Za-z0-9_]好)"
# \w 匹配任意字符,但是和.不一样,\w可以匹配下划线
match_obj = re.match(regex_str3, line3)
if match_obj:
    print(match_obj.group(1))

line4 = "您 好"
regex_str4 = "(您\W好)"
# \W 与\w相反 [A-Za-z0-9_],因为\w不能匹配空格,所以\W就可以匹配空格
match_obj = re.match(regex_str4, line4)
if match_obj:
    print(match_obj.group(1))
  • [\u4E00-\u9FA5]
# 正则表达式:[\u4E00-\u9FA5]() \d 
import re
line = "from xx大学"
regex_str = ".*?([\u4E00-\u9FA5]+大学)"
# 固定写法,匹配汉字
match_obj = re.match(regex_str, line)
if match_obj:
    print(match_obj.group(1))

line2 = "您好,2001年"
regex_str2 = ".*?(\d+)年"
# 匹配连续的数字,?取消非贪婪,从左边开始找,不要从右边往左边
match_obj = re.match(regex_str2, line2)
if match_obj:
    print(match_obj.group(1))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值