Given a regex that looks like this:
_regex_pattern = re.compile(r'["\')]}]+?(?:s+|(?=--)|$)', re.MULTILINE|re.UNICODE)
We can retrieve the flag with:
_regex_pattern.flags # outputs "40"
And retrieve the pattern with:
_regex_pattern.pattern # '["\')]}]+?(?:s+|(?=--)|$)'
If we want to store the regex into some kind of json, we will do something like:
_regex_json = {'pattern': _regex_pattern.pattern, 'flags': _regex_pattern.flags}
with open('regex.json', 'w') as fout:
json.dump(_regex_json, fout)
But when we want to load the pattern, other than pickling, how do we convert the IntFlag to the regex flag?
with open('regex.json') as fin:
_regex_json = json.load(fin)
_regex_pattern_loaded = re.compile(_regex_json['pattern'].encode('unicode_escape'), ???)
P/S: Pickling is not a viable solution for this task, since we’re literally going to compile something here, it’s not safe.