【发布时间】:2017-02-22 03:36:15
【问题描述】:
我想在我的 django 项目中验证用户的 cmets。 在 cmets 中,这些字符是不允许的: [ * % & ! ='; ` ]
最好的正则表达式是什么?
【问题讨论】:
-
只是想知道你为什么不允许这些字符?
标签: python regex django validation
我想在我的 django 项目中验证用户的 cmets。 在 cmets 中,这些字符是不允许的: [ * % & ! ='; ` ]
最好的正则表达式是什么?
【问题讨论】:
标签: python regex django validation
非常精确地遵循您的规范,正则表达式 ^[^\[\]*%&!=\';`]*$ 完全符合您的描述。它匹配:
^ the start of the string
[^ any character that is not:
*%&!=\';` any of: [ ] * % & ! = ' ; `
]* 0 or more times
$ the end of the string
所以在python中,
import re
pattern = re.compile(r'^[^\[\]*%&!=\';`]*$')
if pattern.match(my_string):
print('this is a valid comment')
else:
print('this is an invalid comment')
(请注意,您的用户可能会对他们的 cmets 中为什么不惊呼!也感到困惑。另外,如果您不想匹配空字符串,请使用 + 而不是 *:^[^\[\]*%&!=\';`]+$)
【讨论】:
【讨论】: