Home > Mobile >  Python Regex to get key values seperated by colon
Python Regex to get key values seperated by colon

Time:03-22

I have a data file which contains a string key: value pair seperated by colon. Example:

data=" System Description: Managed SF4503
    System Up Time (days,hour:min:sec): 00:00:04:33
    System Contact: 
    System Name: testname
    System Location: 
    System MAC Address: 00:00:00:00:00:00
    System Object ID: 1.2.4.5.6.7.8.9.0"

I am trying to create a regex in python to fetch the values using keys from the above mentioned data.

Expected output:

data['System Description'] = Managed SF4503
data[ 'System Name'] = testname

like wise

Could anyone help me out with the regex pattren to achieve the expected output.

CodePudding user response:

Since you are just splitting on single characters a regex is not needed. Pythons split method can be used to achieve the required result

result = {}
for entry in data.split('\n'):
  key, value = entry.split(':', 1)
  result[key.strip()]  =value.strip()
result

result:

{'System Contact': '',
 'System Description': 'Managed SF4503',
 'System Location': '',
 'System MAC Address': '00:00:00:00:00:00',
 'System Name': 'testname',
 'System Object ID': '1.2.4.5.6.7.8.9.0',
 'System Up Time (days,hour': 'min:sec): 00:00:04:33'}

CodePudding user response:

If we suppose that we cannot have ": " in keys or values, then a simple (.*): (.*) would do the job (along with regex MULTIPLE flag).

Here is an example in Python:

import re

pattern = re.compile(r"(.*): (.*)", re.MULTIPLE)

s = """System Description: Managed SF4503
System Up Time (days,hour:min:sec): 00:00:04:33
System Contact: 
System Name: testname
System Location: 
System MAC Address: 00:00:00:00:00:00
System Object ID: 1.2.4.5.6.7.8.9.0"""

couples = pattern.findall(s)
print(couples)

data = dict(couples)
print(data)

Result:

[('System Description', 'Managed SF4503'), ('System Up Time (days,hour:min:sec)', '00:00:04:33'), ('System Contact', ''), ('System Name', 'testname'), ('System Location', ''), ('System MAC Address', '00:00:00:00:00:00'), ('System Object ID', '1.2.4.5.6.7.8.9.0')]

{'System Description': 'Managed SF4503', 'System Up Time (days,hour:min:sec)': '00:00:04:33', 'System Contact': '', 'System Name': 'testname', 'System Location': '', 'System MAC Address': '00:00:00:00:00:00', 'System Object ID': '1.2.4.5.6.7.8.9.0'}
  • Related