我有以下正则表达式:
codes = re.findall(r"\">([a-zA-Z0-9]{4}) ", source_code)
这将返回由数字或字母组成的任何4个字符的术语,但是我只想返回包含至少一个数字的术语。有人可以告诉我我应该使用的代码吗?
答案 0 :(得分:0)
这是使用Positive Lookahead:
的那个\">(?=.*\d)([a-zA-Z\d]{4})
regex101处的测试用例。
但是,更容易理解的是,您可以先使用当前正则表达式捕获,然后使用\d+
正则表达式检查结果是否包含至少1个数字。
可运行的Python程序here:
import re
regex = r"\">(?=.*\d)([a-zA-Z\d]{4})"
test_str = ("\">abcda\n"
"\">1111a\n"
"\">ab1da\n"
"\">abc2a\n"
"\">3bcda\n"
"\">a2cda")
matches = re.finditer(regex, test_str)
for matchNum, match in enumerate(matches):
print (match.group(1))