我是Python的初学者,我喜欢用“ null”表达式替换动态正则表达式:例如,用空值替换正则表达式“ [[1-9] | \ d {2,}或\ w {2 /}”:
list_regex=["num=([1-9]|\d{2,})","<urn:rental>\w{2,}</urn:rental>"]
如何在不使用“替换”的情况下动态地执行此操作?结果必须是这样的:
list_regex=["num=null","<urn:rental>null</urn:rental>"]
你能帮助我吗?先感谢您。
写下您的正则表达式,使得他们可以.format
“d成
list_regex = [r"num={}", r"<urn:rental>{}</urn:rental>"]
replacement_options = {
"name1": (r"([1-9]|\d{2,})", r"\w{2,}"),
"nulls": ("null", "null"),
}
def test_many(inputs_list, list_regex, replacement_options):
for name, replacers in replacement_options.items():
match_group = []
for index, replacer in enumerate(replacers):
match = re.match(list_regex[index].format(replacer), inputs_list[index])
if not match: # optional test to break out faster
break # continue with next (name, replacer)
match_group.append(match)
if all(match_group):
return name, match_group
raise ValueError("never matched!")
您也可以默认使用 null
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句