1. string.startswith()
從字符串開(kāi)始匹配單個(gè)字符串
strings = ["abc","bcd","cab"]
for s in strings:
if s.startswith("ab"):
print(s)
>>abc
從字符串開(kāi)始匹配多個(gè)字符串,匹配字符串以元祖的形式存儲(chǔ)
strings = ["abc","bcd","cab"]
for s in strings:
if s.startswith(("ab","bc")):
print(s)
>>abc
bcd
2. 正則匹配 re.match()
re.match()
從字符串的開(kāi)始進(jìn)行匹配
Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.
注意:re.match()
的結(jié)果是對(duì)象,需要.group()
獲得匹配結(jié)果
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.文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-546705.html
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
若從字符串開(kāi)始匹配,加"^"文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-546705.html
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 匹配失敗
到了這里,關(guān)于Python 從字符串開(kāi)始匹配的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!