regex - Building a verbose regular expression in python -
i trying build regex depend on variables coming from many different sources.
sources:
dict1 = {"a":"somevalue","b":"somevalue","c":"somevalue"} source2 = "x" source3 = "_1"
i want build regex depend on values above sources. resulting regex below.
^(a|b|c)x[0-9]{0,10}_1
where:
(a|b|c)
keys ofdict1
,dict
can have 1 or more values.x
valuesource2
.-1
valuesource3
.
i not satisfied solution have concatenation sources build regex. wondering if there other better , solution. here solution came with.
group1 = "|".join(dict1.keys()) regex = "^("+group1+")"+source2+"[0-9]{0,10}"+source3
will appreciate help. may re.verbose
? not sure whats best way.
as long expression simple enough can avoid regular expression escape headaches parsing manually:
def parse(s): assert max(len(k) k in dict1) == 1 , len(source2) == 1 #keep simple match = (s[0:1] in dict1 , s[1:2] == source2 , all(c in string.digits c in s[2:-2]) , len(s[2:-2]) <= 10 , s[-2:] == source3) return s[0] if match else none
Comments
Post a Comment