Using regex in python to parse a string for variables names and values
Do you need regex for this? There are clear separators here: / separates key value pairs, and = separates keys from their values.
string = "status=0/eStopStatus=2/version=1.0.16/runTime=005320"
parsed_variables = dict(substring.split("=") for substring in string.split("/"))
print(parsed_variables)
# {'status': '0', 'eStopStatus': '2', 'version': '1.0.16', 'runTime': '005320'}
Here, dict takes an iterable of tuples to convert them to a dict. Specifically:
string.split("/") # this returns a list of elements like 'status=0`
substring.split("=") # this returns a tuple, like ('status', '0')
If you have clear deliminators, use them. Regex behaviour is much more difficult to understand from inspection than splitting on delimiters.
Read more here: Source link
