Proper escape when using regex in JSON (trying to create a spaCy pattern matching file)

Viewed 82

how can I get the JSON for this string to accept the regex expression that also includes a special character ("\")? I have tried a few things and I can't seem to get it to work. I am trying to create a spaCy pattern jsonl file but it keeps puking on this line due to that regx and special character. It is just cases like this that are not working. Obviously user error, I just can't seem to figure out how to properly escape it so it will parse properly. Any input or help would be appreciated.

For this part (?i)SER+-\d+ I have tried escaping (?i)SER+-\\d+ or (?i)SER+-\\\d+ but it doesn't work. 
import json

s = '{"label":"PRODUCT", "pattern": [{"TEXT": {"TEXT": {"REGEX": "(?i)SER+-\d+"}}]}'

print(s)
# parse x:
y = json.loads(s)
1 Answers

You should declare the string literal with the r prefix and use a double backslash to define regex escape sequences:

import json
s = r'{"label":"PRODUCT", "pattern": [{"TEXT": {"REGEX": "(?i)SER+-\\d+"}}]}'
print(s)
# => {"label":"PRODUCT", "pattern": [{"TEXT": {"REGEX": "(?i)SER+-\\d+"}}]}
y = json.loads(s)
print(y)
# => {'label': 'PRODUCT', 'pattern': [{'TEXT': {'REGEX': '(?i)SER+-\\d+'}}]}
print(y["pattern"][0]["TEXT"]["REGEX"])
# => (?i)SER+-\d+

See the online Python demo. I believe you actually want "pattern": [{"TEXT": {"REGEX": "(?i)SER+-\\d+"}}], if you believe you need one more nested TEXT, just add it back.

Note that the double backslashes you see when printing the y value are actually a single backslash, that is why I added the print(y["pattern"][0]["TEXT"]["REGEX"]) line to prove it.

Related