Consolidating regular expression tokens

Viewed 17

I'm looking for a way to take a regular expression and reduce it to its most concise form, or at least make obvious reductions like combining identical tokens into a single token with a quantifier.

For example:

reg_exp_1           = r'...'   # <-- Should match any sequence of 3 characters
reg_exp_1_compacted = r'.{3}'  # same, but more concise

reg_exp_2           = r'.{3}.{5}'  # <-- Should match any sequence of 8 characters
reg_exp_2_compacted = r'.{8}'      # <-- same, but more concise

reg_exp_2           = r'.{3,5}.{2,5}'  # <-- Should match any sequence of 5 to 10 characters
reg_exp_2_compacted = r'.{5,10}'      # <-- same, but more concise

Does such a mechanism exist in python? I thought perhaps re.compile() would do something like that, but re.compile().pattern simply returns the same pattern string I gave it to compile from.

0 Answers
Related