我正在用 Django 构建一个论坛应用程序,我想确保用户不会在他们的论坛帖子中输入某些字符。我需要一种有效的方法来扫描他们的整个帖子以检查无效字符。到目前为止,我所拥有的是以下内容,尽管它不能正常工作,而且我认为这个想法不是很有效。
def clean_topic_message(self):
topic_message = self.cleaned_data['topic_message']
words = topic_message.split()
if (topic_message == ""):
raise forms.ValidationError(_(u'Please provide a message for your topic'))
***for word in words:
if (re.match(r'[^<>/\{}[]~`]$',topic_message)):
raise forms.ValidationError(_(u'Topic message cannot contain the following: <>/\{}[]~`'))***
return topic_message
感谢您的帮助。
最佳答案
对于正则表达式解决方案,这里有两种方法:
- 在字符串中的任意位置找到一个无效字符。
- 验证字符串中的每个字符。
这是一个同时实现了这两者的脚本:
import re
topic_message = 'This topic is a-ok'
# Option 1: Invalidate one char in string.
re1 = re.compile(r"[<>/{}[\]~`]");
if re1.search(topic_message):
print ("RE1: Invalid char detected.")
else:
print ("RE1: No invalid char detected.")
# Option 2: Validate all chars in string.
re2 = re.compile(r"^[^<>/{}[\]~`]*$");
if re2.match(topic_message):
print ("RE2: All chars are valid.")
else:
print ("RE2: Not all chars are valid.")
任你选。
注意:原始正则表达式错误地在需要转义的字符类中有一个右方括号。
基准测试:在看到 gnibbler 使用 set()
的有趣解决方案后,我很想知道这些方法中哪种方法实际上最快,所以我决定对它们进行测量.以下是测量的基准数据和语句以及 timeit
结果值:
测试数据:
r"""
TEST topic_message STRINGS:
ok: 'This topic is A-ok. This topic is A-ok.'
bad: 'This topic is <not>-ok. This topic is {not}-ok.'
MEASURED PYTHON STATEMENTS:
Method 1: 're1.search(topic_message)'
Method 2: 're2.match(topic_message)'
Method 3: 'set(invalid_chars).intersection(topic_message)'
"""
结果:
r"""
Seconds to perform 1000000 Ok-match/Bad-no-match loops:
Method Ok-time Bad-time
1 1.054 1.190
2 1.830 1.636
3 4.364 4.577
"""
基准测试表明选项 1 比选项 2 稍快,并且都比 set().intersection()
方法快得多。对于匹配和不匹配的字符串都是如此。
关于python - 在python中搜索无效字符的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5698267/