[英]Python: Regular expression to match alpha-numeric not working?
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
For some reason, this matches with crazy chars for example: nIg○▲ ☆ ★ ◇ ◆ 出于某种原因,这与疯狂的角色相匹配,例如:nIg○▲☆★◇◆
I only want regular AZ and 0-9 and _ matching, is there something i am missing here? 我只想要常规AZ和0-9和_匹配,这里有什么我想念的吗?
Python has a special sequence \\w
for matching alphanumeric and underscore when the LOCALE
and UNICODE
flags are not specified. 当没有指定
LOCALE
和UNICODE
标志时,Python有一个特殊的序列\\w
用于匹配字母数字和下划线。 So you can modify your pattern as, 所以你可以修改你的模式,
pattern = '^\\w+$'
Your regex only matches one character. 你的正则表达式只匹配一个字符。 Try this instead:
试试这个:
if re.match('^[a-zA-Z0-9_]+$',playerName):
…check if is alpha-numeric and possibly contains an underscore.
...检查是否是字母数字,可能包含下划线。
Do you mean this literally, so that only one underscore is allowed, total? 你的意思是字面意思,所以只允许一个下划线,总数? (Not unreasonable for player names; adjacent underscores in particular can be hard for other players to read.) Should "a_b_c" not match?
(对于玩家名称而言并非不合理;特别是相邻的下划线可能很难被其他玩家阅读。)“a_b_c”不匹配吗?
If so: 如果是这样的话:
if playerName and re.match("^[a-zA-Z0-9]*_?[a-zA-Z0-9]*$", playerName):
The new first part of the condition checks for an empty value, which simplifies the regex. 条件的新第一部分检查空值,这简化了正则表达式。
This places no restrictions on where the underscore can occur, so all of "_a", "a_", and "_" will match. 这对下划线的位置没有限制,因此所有“_a”,“a_”和“_”都匹配。 If you instead want to prevent both leading and trailing underscores, which is again reasonable for player names, change to:
如果您想要同时阻止前导和尾随下划线,这对于玩家名称来说也是合理的,请更改为:
if re.match("^[a-zA-Z0-9]+(?:_[a-zA-Z0-9]+)?$", playerName):
// this regex doesn't match an empty string, so that check is unneeded
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.