问题:
我有这个人工示例函数:
def test_function(target, words):
pattern = re.compile(r"|".join(words))
return bool(pattern.search(target))
它采用单词列表并动态构建正则表达式模式,无需对列表中的单词进行适当的转义。
使用示例:
text = "hello world!"
print(test_function(text, ["test"])) # prints False
print(test_function(text, ["hello"])) # prints True
print(test_function(text, ["test", "world"])) # prints True
问题:
我如何测试此函数以证明没有正确的正则表达式转义或输入清理?
换句话说,我应该提供 words 列表中的哪些项目来“破坏”此功能?
我已经尝试了几个“邪恶”的正则表达式来模拟灾难性的回溯并强制函数像 (x+x+)+y 或 (a+)+ 一样挂起,但该函数只是返回 False 立即 并且没有任何问题的迹象。
请您参考如下方法:
有很多方法可以做到这一点。例如,一个不是有效正则表达式的词:
>>> test_function('a', ['*'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in test_function
File "/usr/lib64/python2.6/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib64/python2.6/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat
或匹配所有内容的单词作为正则表达式:
>>> test_function('a', ['.*'])
True
或者一个不符合正则表达式的词:
>>> test_function('$^', ['$^'])
False
或以反斜杠结尾并转义 | 的单词:
>>> test_function('a', ['\\', 'a'])
False
灾难性回溯也有效:
>>> test_function('a'*100, ['(a+)+b'])
# Hangs.
