我正在写一个正则表达式来匹配带有字母数字字符(“-”,“ AZ”,“ az”,“ 0-9”和“ _”)的字符串,并且该字符串应以字母开头或结尾(“ az”或“ AZ”)或数字(“ 0-9”)
有效字符串的示例:[“ abcd-ef_df”,“ 123_abc-def”,“ abcdef”,“ 12345”]
无效字符串的示例:[“ _abc”,“ abc-”,“ abc $ def”]
我试过下面的表达式,但是它为所有类型的字符串提供了True:
if re.match('(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?', my_str):
print True
使用模式^[^\W_](?:[\w-]*[^\W_])?$
:
my_str = "123_abc-def"
if re.match(r'^[^\W_](?:[\w-]*[^\W_])?$', my_str):
print("MATCH")
这是模式的解释:
^ from the start of the string
[^\W_] match an initial letter or number only
(?: (don't capture)
[\w-]* match zero or or more middle letters, numbers, _ or -
[^\W_] match a closing letter or number only
)? middle and final characters are optional
$ end of the string
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句