replace substring None with 'None'

Go To StackoverFlow.com

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.

2012-04-03 22:56
by daydreamer


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'.

2012-04-03 23:06
by He Shiming
thats what I am doing right now, but I am sure regex can do everything in one sho - daydreamer 2012-04-03 23:08


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 ←

2012-04-03 23:04
by Honest Abe
You are also changing 'None' to ''None''He Shiming 2012-04-03 23:05
@He Shiming Pardon me, I've updated it - Honest Abe 2012-04-03 23:11
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 2012-04-04 00:01
@Gary Fixler Thanks. I agree it's worth mentioning - Honest Abe 2012-04-04 00:09


0

s/([^'])?(None)([^'])?/$1'$2'$3/g
2012-04-03 23:19
by fbdcw
Ads