Python正则表达式可匹配仅包含字母数字,'-'和'_'且不以任何特殊字符开头或结尾的字符的字符串

艾哈迈德·梅拉杰

我正在写一个正则表达式来匹配带有字母数字字符(“-”,“ 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
蒂姆·比格莱森(Tim Biegeleisen)

使用模式^[^\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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档