Fourth, the regular expression: match start and end of

Fourth, the regular expression: match start and end of

^ Limit matching content must be judged from the beginning of the
contents must include the $ matches the end of restrictions
to use re.match () comes the beginning of the judgment, but the judgment is not the end, that is, even in the front part of the match character comply with the limits, if not later service , but also returns the object
, for example: the following two cases can be successfully matched, the three kinds of matching fails

ret = re.match(r"\d{3}", "123")
ret.group()
ret = re.match(r"\d{3}", "12345678")
ret.group()
#如果加上$,则判断结果不匹配
ret = re.match(r"\d{3}$", "12345678")
ret.group()

Integrated Applications:
a string of names to determine whether the variable naming conventions (lowercase or uppercase first letter can underscore _, not a number, can not contain #,!?)

# coding = utf-8
import re


names = ["age", "age_1", "_age__", "____", "2_age", "age!", "ag#e"]
def main():
    for name in names:
        ret = re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$",name)   # ^可加可不加,match自带判断开头
        if ret:
            print("变量名%s符合命名规范,输出结果是:%s" % (name, ret.group()))
        else:
            print("变量名%s不符合命名规范,它在列表的第%s位" % (name, names.index(name)))

if __name__ == "__main__":
    main() 
Published 47 original articles · won praise 74 · views 7904

Guess you like

Origin blog.csdn.net/Jacky_kplin/article/details/104744991