CodeQL 文档

正则表达式中的不可匹配美元符号

ID: py/regex/unmatchable-dollar
Kind: problem
Security severity: 
Severity: error
Precision: high
Tags:
   - reliability
   - correctness
Query suites:
   - python-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

正则表达式中的美元断言 $ 仅匹配输入的结尾,或者(对于多行正则表达式)匹配行的结尾。如果它后面跟着必须匹配非空序列(非换行符)输入字符的模式,则它不可能匹配,从而导致整个正则表达式不可匹配。

建议

检查正则表达式,查找并更正任何拼写错误。

示例

在以下示例中,正则表达式 r"\.\(\w+$\)" 无法匹配任何字符串,因为它包含一个美元断言,后面跟着一个匹配右括号的转义序列。

第二个正则表达式 r"\.\(\w+\)$" 将美元符号放在末尾,并将按预期工作。

import re
#Regular expression that includes a dollar, but not at the end.
matcher = re.compile(r"\.\(\w+$\)")

def find_it(filename):
    if matcher.match(filename):
        print("Found it!")

#Regular expression anchored to end of input.
fixed_matcher = re.compile(r"\.\(\w+\)$")

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私