Python:匹配字母数字的正则表达式不起作用? [英] Python: Regular expression to match alpha-numeric not working?

查看:46
本文介绍了Python:匹配字母数字的正则表达式不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望匹配从网站输入的字符串,以检查是否为字母数字并且可能包含下划线.我的代码:

I am looking to match a string that is inputted from a website to check if is alpha-numeric and possibly contains an underscore. My code:

if re.match('[a-zA-Z0-9_]',playerName):
            # do stuff

出于某种原因,这与疯狂的字符匹配,例如:nIg○▲ ☆ ★ ◇ ◆

For some reason, this matches with crazy chars for example: nIg○▲ ☆ ★ ◇ ◆

我只想要常规的 A-Z 和 0-9 和 _ 匹配,我在这里缺少什么吗?

I only want regular A-Z and 0-9 and _ matching, is there something i am missing here?

推荐答案

Python 有一个特殊的序列 \w 用于在 LOCALE 时匹配字母数字和下划线未指定 UNICODE 标志.所以你可以修改你的模式,

Python has a special sequence \w for matching alphanumeric and underscore when the LOCALE and UNICODE flags are not specified. So you can modify your pattern as,

pattern = '^\w+$'

这篇关于Python:匹配字母数字的正则表达式不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆