How to serialize a regex to json in python? -


i'm building api in python accepts regexes , needs able serialize compiled regexes original string in json response. i've looked around haven't found obvious method of accessing raw regex compiled regex:

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

one approach came create custom regex class mirrors functionality provides access raw property 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 doesn't seem give me access methods of compiled regex.

the last option, may have go with, mirroring methods in 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 seems wholly inelegant. there better solution?

you can access raw regex string via pattern property:

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

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -