V
V
Vyacheslav2019-06-24 13:01:07
Python
Vyacheslav, 2019-06-24 13:01:07

How to write a regex to a json file and read it without losing the r prefix?

I need to save a regular expression like this
rg = r"expression"
to a json. "expression"- any regular expression. Expressions must be added to the list.
Now I am using json.dump(expression_list, file). As a result, the
{"rg_list": ["expression"]}
task is as follows: read the expression from the list nested in jsonso that the read expression begins with the prefix r. How to do it right and what other pitfalls should be foreseen?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Yakushenko, 2019-06-24
@ElefanObi

No way. In JSON, all strings must be in double quotes. Yes, and this does not make much sense, which prevents you from using something like this in the right place in Python:

pattern = re.compile(r'{}'.format(json['pattern']))

D
DDDsa, 2019-06-24
@DDDsa

Wait, the prefix ris ​​just syntactic sugar, not some special type of string. r'abc'for the interpreter, this is not an "r-string", but simply an instruction to escape all special characters and combinations of characters and return the result as a regular string. Which can be saved in JSON, loaded from JSON without loss.
That is, if we write r'a\nb\tc', this is the same as if we wrote. 'a\\nb\\tc'
In other words, you just need to save the data in JSON with the prefix r. After that, they can be loaded back from JSON with full confidence that you will not lose anything

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question