简体   繁体   English

验证数字和字母

[英]Validate both numbers and letters

There have been cases where I have needed to validate a string filled with numbers and letters and I want to know the easiest way to do it 在某些情况下,我需要验证包含数字和字母的字符串,并且我想知道最简单的方法

For example, in Tic Tac Toe / Noughts and Crosses, I need to make sure that the position that the user has entered is between "1-3" and "ac" 例如,在井字游戏/ Noughts and Crosss中,我需要确保用户输入的位置在“ 1-3”和“ ac”之间

For better understanding of what I am asking: 为了更好地理解我的要求:

pos = "2c"
>>> Input is valid

pos = "1z"
>>> Input is invalid: Letters outside range a-c

pos = "5b"
>>> Input is invalid: Numbers outside range 1-3

There are only 9 possible valid inputs, so you could just check them all, or you could use a regular expression to see if the input matches all the valid inputs. 只有9个可能的有效输入,因此您可以全部检查它们,也可以使用正则表达式查看输入是否与所有有效输入匹配。

import re

pattern = re.compile(r'^[123][abc]$')
m = pattern.match("2b")
if m:
    print("It's a match!")

The regular expression r'^[123][abc]$' looks for the start of a string, followed by 1, 2, or 3, followed by a, b, or c, followed by the end of the string. 正则表达式r'^[123][abc]$'寻找字符串的开头,然后是1、2或3,然后是a,b或c,然后是字符串的结尾。 No inputs outside that range (or that are longer than two characters) should match. 超出此范围(或超过两个字符)的任何输入都不应匹配。

Without regular expressions, you could have something like: 没有正则表达式,您可能会遇到以下情况:

def validate(i):
    if type(i) != str or len(i) != 2:
        return False
    d, char = int(i[0]), i[1]
    return d >= 1 and d <= 3 and char in 'abc'

print(validate('1c')) #True
print(validate('3a')) #True
print(validate('2b')) #True

print(validate('36')) # False
print(validate('106')) # False
print(validate('10c')) # False
print(validate(10)) # False

This does, however, assume that the first character in your input can be converted to an int . 但是,这确实假定输入中的第一个字符可以转换为int

Use regex as follows: 使用正则表达式如下:

import re

example_str = '1c'
p = re.compile('^[1-3][a-c]$')

if p.match(example_str):
  # Valid
else:
  # Invalid

You can use - for range selection in pattern. 您可以使用-在模式中选择范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM