0

I just want to fetch port value from cmd_resp.

    cmd_resp = '{ "toolkitStruct":{ "access_ctrl":{ "restricted":false, "disabled":false, "port":8001 }, "description":"EdgeX dev UI and API gateway (authenticated)", "label":"EdgeX API Gateway/UI" } }'
    output = cmd_resp.split('"port":')[1].split(',')[0]
    output = re.sub(r"[\}]", '', output).strip()

My way, I have achieved output = '8001' but can I get the same in more cleaner way? please suggest. Additionally: And what, If need to save {"port":8001}?

1 Answers1

0

https://docs.python.org/3/library/re.html?highlight=re#module-re

(?<=...) Matches if the current position in the string is preceded by a match for ... that ends at the current position. This is called a positive lookbehind assertion. (?<=abc)def will find a match in 'abcdef', since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that abc or a|b are allowed, but a* and a{3,4} are not.

output = re.search('(?<="port":)[0-9]*', cmd_resp)[0]
Raibek
  • 558
  • 3
  • 6