简体   繁体   中英

How to serialize a regex to json in python?

I'm building an API in python which accepts regexes and needs to be able to serialize the compiled regexes back to the original string in a json response. I've looked around but haven't found an obvious method of accessing the raw regex from a compiled regex:

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

One approach I came up with was to create a custom Regex class that mirrors all functionality but provides access to a raw property which I could fallback on 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 methods of a compiled regex.

The last option, which I may have to go with, is simply mirroring 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 wholly inelegant. Is there a better solution?

You can access the raw regex string via the pattern property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM