繁体   English   中英

在python中验证注释的最佳正则表达式是什么?

[英]What's the best regex for validating a comment in python?

我想在我的django项目中验证用户的评论。 在注释中,不允许使用以下字符:[*%&! ='; `]

最好的正则表达式是什么?

这将仅允许单词和空格。 如果包含特殊字符,它将被丢弃。

在这里检查这个正则表达式

^(?!\!\%\!\=\'\;\`)[\w\s\.\?\,]+$

非常精确地遵循您的规范,正则表达式^[^\\[\\]*%&!=\\';`]*$完全符合您的描述。 它匹配:

^              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')

(请注意,您的用户可能会对为什么他们的注释不满意而感到困惑。此外,如果您不想匹配空字符串,请使用+而不是*^[^\\[\\]*%&!=\\';`]+$

暂无
暂无

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

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