0

I want to change any None to 'None' (note single quotes) in a JSON file that contains both already.

type: None or
type: 'None'

I tried "s/[']?None[']?/'None'/g" but it doesn't seem to work.

0

3 Answers 3

3

Since you are changing all None to 'None', wouldn't it be easier to just use str.replace with that json string? I'd run it in two procedures, first change 'None' to None, then change all None to 'None'.

Sign up to request clarification or add additional context in comments.

1 Comment

thats what I am doing right now, but I am sure regex can do everything in one shot
2

You could use a negative lookahead assertion (?!...):

import re

test = "type: None or 'None'"

result = re.sub(r"None(?!')", r"'None'", test)

This will match None as long as it is not directly followed by a '.

→ Regular Expression Syntax ←

3 Comments

You are also changing 'None' to ''None''
Your second example replaces whatever is immediately before or after None with ' characters. Something like "(1,None,2)" would become "(1'None'2)". This may not be a problem in the original JSON file, as there may always be spaces around instances of None, but I thought it was worth mentioning.
@Gary Fixler Thanks. I agree it's worth mentioning.
0
s/([^'])?(None)([^'])?/$1'$2'$3/g

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.