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 匹配失败

你可能感兴趣的:(Python,python,开发语言)