Home > other >  How to use regex to dynamically find a value in a file in Python
How to use regex to dynamically find a value in a file in Python

Time:03-06

I have a long string like this for example:

V:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_CANDY_MACHINE_ID:"9mn5duMPUeNW5AJfbZWQgs5ivtiuYvQymqsCrZAenEdW",REACT_APP_SOLANA_NETWORK:"mainnet-beta

and I need to get the value of REACT_APP_CANDY_MACHINE_ID with regex, the value of it is always 44 characters long so that is a good thing I hope. Also the file/string im pulling it from is much much longer and the REACT_APP_CANDY_MACHINE_ID appears multiple times but it doesnt change

CodePudding user response:

You don't need regex for that, just use index() to get the location of REACT_APP_CANDY_MACHINE_ID.

data = 'V:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0,REACT_APP_CANDY_MACHINE_ID:"9mn5duMPUeNW5AJfbZWQgs5ivtiuYvQymqsCrZAenEdW",REACT_APP_SOLANA_NETWORK:"mainnet-beta'

key = "REACT_APP_CANDY_MACHINE_ID"
start = data.index(key)   len(key)   2

print(data[start: start   44])
# 9mn5duMPUeNW5AJfbZWQgs5ivtiuYvQymqsCrZAenEdW
  • Related