Python正则表达式1

来自CloudWiki
跳转至: 导航搜索

Python10-20.png

import re

line = "bobby123"
#以b开头,重复任意多个字符
regex_str = "^b.*"
if re.match(regex_str,line):
    print("yes")

#以3结尾
regex_str2 ="3$"
if re.match(regex_str,line):
    print("yes")

#从右侧向左,贪婪匹配
line2 ="boooooobby123"
regex_str = ".*(b.*b).*"
match_obj = re.match(regex_str,line2)
if match_obj:
    print(match_obj.group(1))

#从左边开始,非贪婪匹配

line3 ="boooooobby123"
regex_str = ".*?(b.*?b).*"
match_obj = re.match(regex_str,line3)
if match_obj:
    print(match_obj.group(1))