正则表达式中特殊组缺少部分¶
ID: py/regex/incomplete-special-group
Kind: problem
Security severity:
Severity: warning
Precision: high
Tags:
- reliability
- correctness
Query suites:
- python-security-and-quality.qls
使用正则表达式的一个问题是,几乎任何字符序列都是有效的模式。这意味着很容易省略一个必要的字符,而仍然得到一个有效的正则表达式。省略命名捕获组中的一个字符是一个特定的情况,它会极大地改变正则表达式的含义。
建议¶
检查正则表达式以查找并纠正任何拼写错误。
示例¶
在以下示例中,matcher
的正则表达式,r"(P<name>[\w]+)"
,缺少一个“?”,只会匹配以“P<name>”开头的字母字符串,而不是匹配任何字母序列并将结果放入命名组。修正后的版本,fixed_matcher
,包含了“?”,并将按预期工作。
import re
matcher = re.compile(r'(P<name>[\w]+)')
def only_letters(text):
m = matcher.match(text)
if m:
print("Letters are: " + m.group('name'))
#Fix the pattern by adding the missing '?'
fixed_matcher = re.compile(r'(?P<name>[\w]+)')