Python 从字符串开始匹配

1. string.startswith()

从字符串开始匹配单个字符串

strings = ["abc","bcd","cab"]

for s in strings:
    if s.startswith("ab"):
        print(s)
>>abc

从字符串开始匹配多个字符串,匹配字符串以元祖的形式存储

strings = ["abc","bcd","cab"]

for s in strings:
    if s.startswith(("ab","bc")):
        print(s)
>>abc
bcd

2. 正则匹配 re.match()

re.match() 从字符串的开始进行匹配

Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.
注意:re.match()的结果是对象,需要.group()获得匹配结果

strings = ["abc","bcd","cab"]

for s in strings:
    result = re.match(r"ab|bc", s)
    print(result)
    if(result):
        print(s, result.group())
    else:
        print(s, "匹配失败")

>>
<re.Match object; span=(0, 2), match='ab'>
abc ab
<re.Match object; span=(0, 2), match='bc'>
bcd bc
None
cab 匹配失败

3. 正则匹配 re.search()

re.search() 从字符串的任意位置匹配

Scan through string looking for a match to the pattern, returning a Match object, or None if no match was found.

strings = ["abc","bcd","cab"]

for s in strings:
    result = re.search(r"ab|bc", s)
    print(result)
    if(result):
        print(s, result.group())
    else:
        print(s, "匹配失败")
>>
<re.Match object; span=(0, 2), match='ab'>
abc ab
<re.Match object; span=(0, 2), match='bc'>
bcd bc
<re.Match object; span=(1, 3), match='ab'>
cab ab

若从字符串开始匹配,加"^"

strings = ["abc","bcd","cab"]

for s in strings:
    result = re.search(r"^ab|^bc", s)
    print(result)
    if(result):
        print(s, result.group())
    else:
        print(s, "匹配失败")

>>
<re.Match object; span=(0, 2), match='ab'>
abc ab
<re.Match object; span=(0, 2), match='bc'>
bcd bc
None
cab 匹配失败
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值