python - re.rompile 返回 true 和 false,不允许使用符号

标签 python

我尝试使用正则表达式检查变量是否接受字母和数字。这是我的定义:

def special_match(strg, search=re.compile(r'[a-z0-9]').search):
 if bool(search(strg)) is True:
    print ('Yes: ' + strg)
 elif:
    print ('nej: ')

while 1:
    variabel = raw_input('Enter something: ')
    special_match(variabel)

sys.exit()

似乎接受不允许符号与允许符号的组合:

Enter something: qwerty
Yes: qwerty
Enter something: 1234
Yes: 1234
Enter something: !!!!      
nej!
Enter something: 1234qwer!!!!
Yes: 1234qwer!!!!
Enter something: 

最后一个不应该被接受..我做错了什么?

最佳答案

所有正则表达式搜索所做的就是检查是否至少存在一个字符。

如果你想要求整个字符串只包含这些字符,那么你可以使用:

r'^[a-z0-9]*$'

它将模式锚定在字符串的开头和结尾,并且仅当中间的所有字符都在指定的字符集中时才匹配。

请注意,这也将匹配空字符串。如果您希望至少需要一个字符,则可以将 * 更改为 +

关于python - re.rompile 返回 true 和 false,不允许使用符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35600918/

相关文章:

python - 如何在Python中使用锁允许多个线程更改对象的不同部分?

python - 使用行为进行 API 端点测试

python - iter() 对列表做了什么?

python - 为 Python 数据类编写装饰器

Python Scrapy 在每个 process_item 上维护 SSH MySQL 连接

python - 在 Python 中,如何将 3D 等值面导出到 Blender

python - 单元测试二分搜索

python - Python 中列表推导式中的哈希函数

python - 使用 numpy 数组时如何消除 for 循环并使用列表理解?

python - 类型错误 : '_TupleWrapper' object is not callable when I run the object detection model ssd