How to serialize regex for json in python?

I am creating an API in python

which accepts regular expressions and should be able to serialize the compiled regular expressions back to the original string in the response json

. I looked around but couldn't find an obvious method to access the raw regex from the compiled regex:

import re 
regex = re.compile(r".*")
# what now?

      

One approach I came up with was to create a custom class Regex

that reflects all the functionality, but provides access to a property raw

that I could defer when serializing:

import re 

class SerializableRegex(object):
    def __init__(self, regex):
        self.raw = regex 
        self.r = re.compile(regex)
        self.r.__init__(self)

      

However, this doesn't seem to give me access to the compiled regex methods.

The last option I might need to with just mirrors all methods in my custom class:

import re 

class SerializableRegex(object):
    def __init__(self, regex):
        self.raw = regex 
        self.r = re.compile(regex)
        self.r.__init__(self)

    def match(self, *args, **kwargs):
         return self.r.match(*args, **kwargs)
    ...

      

However, this seems completely inelegant. Is there a better solution?

+3


source to share


1 answer


You can access the original string of the regex using the property pattern

:



import re
regex_str  = '.*'
regex = re.compile(regex_str)
assert(regex_str == regex.pattern)

      

+6


source







All Articles