您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在python中搜索无效字符的有效方法

在python中搜索无效字符的有效方法

对于正则表达式解决方案,这里有两种方法

这是同时实现这两个功能的脚本:

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 2022/1/1 18:38:23 有244人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶