[英]How would you validate a string to check if it follows this format?
I would like to check if the string stored in the variable, Username is stored in the following format:我想检查存储在变量中的字符串,用户名是否以以下格式存储:
"a.bcde" or "12a.bcde" “a.bcde”或“12a.bcde”
Before the full stop, there can be a single letter or two numbers and a letter.在句号之前,可以有一个字母或两个数字和一个字母。
After the full stop, there can only be letters.句号之后,只能是字母。
Valid Strings: "a.bcdefghi","45z.yxwu"有效字符串:“a.bcdefghi”、“45z.yxwu”
Invalid Strings: "1a.bcdef","12a.bcde@"无效字符串:“1a.bcdef”、“12a.bcde@”
I had written the following code我写了以下代码
if bool(re.match("..[a-z][.][a-z]+", Username))==True:
return True
else:
return False
However, it returns False for "a.bcde" and True for "12a.bcde@fgh.com"但是,它为“a.bcde”返回 False,为“12a.bcde@fgh.com”返回 True
You can use您可以使用
^(?:\d{2})?[a-z][.][a-z]+$
^
Start of string ^
字符串开头(?:\d{2})?
Optionally match 2 digits[az][.]
Match a single char az and .
[az][.]
匹配单个字符 az 和.
[az]+
Match 1+ chars az [az]+
匹配 1+ 个字符 az$
End of string $
字符串结尾Regex demo |正则表达式演示| [Python demo(https://ideone.com/k2Hk81)]
[Python演示(https://ideone.com/k2Hk81)]
For example例如
import re
pattern = r"(?:\d{2})?[a-z][.][a-z]+$"
strings = [
"a.bcde",
"12a.bcde",
"a.bcdefghi",
"45z.yxwu",
"1a.bcdef",
"12a.bcde@"
]
for s in strings:
m = re.match(pattern, s)
if m:
print("Match for {0}".format(m.group()))
Output Output
Match for a.bcde
Match for 12a.bcde
Match for a.bcdefghi
Match for 45z.yxwu
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.