1
votes

I have the following string: "FIELDS--> FIELD1: \r\n FILED2: \r\nSOURCEFIELDS--> KEY1: VALUE1, KEY2: VALUE2, KEY3: VALUE3\r\"

I want would want the following from the above string:

[FIELD1, ]
[FIELD2, ]
[KEY1, VALUE1]
[KEY2, VALUE2]
[KEY3, VALUE3]

So I still want the value if its empty. It will be empty sometimes and other times it won't. Also the amount of fields may vary.

I have tried:

x= 'FIELDS--> FIELD1:  \r\n FILED2: \r\nSOURCEFIELDS--> KEY1: VALUE1, KEY2: VALUE2, KEY3: VALUE3\r\n'
   x.split(':')
1
@WiktorStribiżew Almost perfectly works. How do I handle it if the value has dots, and dashes? - Kalimantan
Thanks! If you post the answer I'll accept it. - Kalimantan

1 Answers

2
votes

You may use

re.findall(r'(\w+) *:(?: *([\w.-]+))?', x)

See the regex demo.

Details

  • (\w+) - Group 1: one or more word chars
  • *: - 0 or more spaces and a :
  • (?: *([\w.-]+))? - an optional sequence of
    • * - 0 or more spaces
    • ([\w.-]+) - Group 2: one or more word, . or - chars.