CodeQL 文档

正则表达式中无法匹配的插入符

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

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

插入符字符 ^ 将正则表达式锚定到输入的开头,或者(对于多行正则表达式)锚定到行的开头。如果它之前是一个模式,该模式必须匹配一个非空的(非换行符)输入字符序列,那么整个正则表达式将无法匹配任何内容。

建议

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

示例

在以下示例中,正则表达式 r"\[^.]*\.css" 无法匹配任何字符串,因为它包含一个插入符断言,它之前是一个匹配左括号的转义序列。

在第二个正则表达式 r"[^.]*\.css" 中,插入符是字符类的一部分,并且不会匹配字符串的开头。

import re
#Regular expression includes a caret, but not at the start.
matcher = re.compile(r"\[^.]*\.css")

def find_css(filename):
    if matcher.match(filename):
        print("Found it!")
        
#Regular expression for a css file name
fixed_matcher_css = re.compile(r"[^.]*\.css")

参考资料

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