简体   繁体   中英

Trying to convert Sed command to Python re.sub

I am trying to convert the below Sed command to python re.sub. The Sed command is basically extracting the access_token value from the json string.

finalString=$(echo $initialString |  sed -e 's/^.*"access_token":"\([^"]*\)".*$/\1/')

My Python code, I was stuck in replacing the \\1 part. I have to replace the whole string with the value

access_token = re.sub('^.*"access_token":"\([^"]*\)".*$',r'\1',initialString)
print access_token

My working echo statement is as follows, When I run this I am getting the access_token value. For Ex: If initialString ='{"access_token":"xyz"}' output will be xyz .

echo initialString | sed -e 's/^.*"access_token":"\([^"]*\)".*$/\1/'

In general, you should make it a rule to always use raw-strings as regular expressions in Python. (In specific, it doesn't matter here. But it's a good rule of thumb.)

Try this:

access_token = re.sub(r'^.*"access_token":"([^"]*)".*$', r'\1', initialString)

I'm working on the assumption that your intialString is something along the lines of: "other":"json","access_token":"(1234)","more":"json"

access_token = re.sub(r'^.*"access_token":"\(([^\)]*)\)".*$',r'\1',initialString)

The problem I noticed was that you were never actually capturing any characters to reference with \\1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM