对于正则表达式解决方案,这里有两种方法:
- 在字符串中的任意位置找到一个无效字符。
- 验证字符串中的每个字符。
这是同时实现这两个功能的脚本:
import retopic_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-time1 1.054 1.1902 1.830 1.6363 4.364 4.577"""
基准测试表明,选项1的速度比选项2的速度略快,并且两者均比
set().intersection()方法快得多。对于匹配和不匹配的字符串都是如此。



