根据提供的代码(本文简化),有人可以帮助说明我如何获取正则表达式模式的列表(如果“ list”是要使用的正确类型)从文本文件加载并与之匹配一个字符串?
有很多从文件中加载文本/文本字符串并与正则表达式模式匹配的示例,但并非相反-许多正则表达式模式都与一个文本字符串匹配。
如果您手动创建一个列表并运行re.compile,您可能会在代码中看到,我可以使用模式列表来匹配字符串。但是,从文件加载时,re.compile在哪里适合?
import regex as re
fname = 'regex_strings_short.txt'
string_to_match = 'onload=alert'
# Create a manual list of regexes
manual_regexes = [
re.compile(r'(?i)\bHP\b(?:[^.,;]{1,20}?)\bnumber\b'),
re.compile(r'(?i)\bgmail\b(?:[^.,;]{1,20}?)\bnumber\b'),
re.compile(r'(?i)\bearthlink\b(?:[^.,;]{1,20}?)\bnumber\b '),
re.compile(r'(?i)onload=alert')
]
# Create a text file with these five example patterns
'''
(?i)\bHP\b(?:[^.,;]{1,20}?)\bnumber\b
(?i)\bgmail\b(?:[^.,;]{1,20}?)\bnumber\b
(?i)\bearthlink\b(?:[^.,;]{1,20}?)\bnumber\b
(?i)onload=alert
(?i)hello
'''
# Import a list of regex patterns from the created file
with open(fname, 'r') as file:
imported_regexes = file.readlines()
# Notice the difference in the formatting of the manual list with 'regex.Regex' and 'flags=regex.I | regex.V0' wrapping each item
print(manual_regexes)
print('---')
print(imported_regexes)
# A match is found in the manual list, but no match found in the imported list
if re.match(imported_regexes[3], my_string):
print('Match found in imported_regexes.')
else:
print('No match in imported_regexes.')
print('---')
if re.match(manual_regexes[3], my_string):
print('Match found in manual_regexes.')
else:
print('No match in manual_regexes.')
imported_regexes不匹配,manual_regexes不匹配。
更新:以下代码是对我有用的最终解决方案。将其发布可能会帮助某人登陆并需要解决方案。
# You must use regex as re and not just 'import re' as \p{} is not correctly escaped
import regex as re
# Add the post/string to match below
my_string = '<p>HP Support number</p>'
fname = 'regex_strings.txt'
# Contents of text file similar to the below
# but without the leading # space - that's only because it's an inline comment here
# (?i)\bHP\b(?:[^.,;]{1,20}?)\bnumber\b
# (?i)\bgmail\b(?:[^.,;]{1,20}?)\bnumber\b
# (?i)】\b(?:[^.,;]{1,1000}?)\p{Lo}
# Import a list of regex patterns from a file
with open(fname, 'r', encoding="utf8") as f:
loaded_patterns = f.read().splitlines()
# print(loaded_patterns)
print(len(loaded_patterns))
found = 0
for index, pattern in enumerate (loaded_patterns):
if re.findall(loaded_patterns[index],my_string):
print('Match found. ' + loaded_patterns[index])
found = 1
if found == 0:
print('No matching regex found.')
答案 0 :(得分:1)
re.match
接受字符串以及已编译的正则表达式作为参数,并将内部字符串转换为已编译的正则表达式对象。您可以出于优化目的而调用re.compile
(多次调用相同的正则表达式),但这纯粹是可选的,以保证程序的正确性。
如果程序未打印出匹配的导入正则表达式,那是因为readlines()
始终在字符串中尾随'\n'
。因此re.match('(?i)onload=alert\n')
返回False
并带有要匹配的字符串。您可以在经过清理的字符串上调用re.compile,也可以不调用。
with open(fname, 'r') as file:
imported_regexes = file.readlines()
print(re.match(imported_regexes[3].strip('\n'), string_to_match))
输出一个matchobject。