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 of dict1 , dict can have 1 or more values.

  • x value source2.

  • -1 value source3.

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

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -