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.文章来源:https://www.toymoban.com/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
若从字符串开始匹配,加"^"文章来源地址https://www.toymoban.com/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 匹配失败
到了这里,关于Python 从字符串开始匹配的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!