[英]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. 我正在
python
构建一个API,它接受正则表达式,并且需要能够将编译的正则表达式序列化回json
响应中的原始字符串。 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: 我提出的一种方法是创建一个自定义
Regex
类,它反映所有功能,但提供对raw
属性的访问,我可以在序列化时使用该属性:
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: 您可以通过
pattern
属性访问原始正则表达式字符串:
import re
regex_str = '.*'
regex = re.compile(regex_str)
assert(regex_str == regex.pattern)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.