Associated with a character format
character | Features |
---|---|
* | A character appears zero or infinity times before the match, that is dispensable |
+ | A character appears once or unlimited times before the match, that is at least 1 |
? | Matches the preceding character appear more than once or zero times, that there is either 1 or none |
{m} | M times a character appears before match |
{m,n} | Before a matching character appears from m to n times |
Example 1: *
Demand: matched, a string of characters to the size of the first letter, and later all lowercase these optional lowercase
#coding=utf-8
import re
ret = re.match("[A-Z][a-z]*","M")
print(ret.group())
ret = re.match("[A-Z][a-z]*","MnnM") print(ret.group()) ret = re.match("[A-Z][a-z]*","Aabcdef") print(ret.group())
operation result:
M
Mnn
Aabcdef
Example 2: +
Requirements: a matching variable name is valid
#coding=utf-8
import re
names = ["name1", "_name", "2_name", "__name__"] for name in names: ret = re.match("[a-zA-Z_]+[\w]*",name) if ret: print("变量名 %s 符合要求" % ret.group()) else: print("变量名 %s 非法" % name)
operation result:
变量名 name1 符合要求
变量名 _name 符合要求
变量名 2_name 非法
变量名 __name__ 符合要求
Example 3 :?
Demand: matching the number between 0 to 99
#coding=utf-8
import re
ret = re.match("[1-9]?[0-9]","7")
print(ret.group())
ret = re.match("[1-9]?\d","33") print(ret.group()) ret = re.match("[1-9]?\d","09") print(ret.group())
operation result:
7
33
0 # 这个结果并不是想要的,利用$才能解决
Example 4: {m}
Requirements: a match, 8-20 passwords are case letters, numbers, underscores
#coding=utf-8
import re
ret = re.match("[a-zA-Z0-9_]{6}","12a3g45678")
print(ret.group())
ret = re.match("[a-zA-Z0-9_]{8,20}","1ad12f23s34455ff66") print(ret.group())
operation result:
12a3g4
1ad12f23s34455ff66