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?
source to share