Skip to content
Advertisement

How to extract exact match from list of strings in Python into separate lists

This is an example list of strings

JavaScript

I would like to extract XIC(Switch_A) into one list, OTE(Light1) into another list, TON(Motor_timer) into another list and so on.

This is the code in Python 3 that I have tried

JavaScript

How do I go about extracting OTE(Tag name), XIC(Tag name), XIO(Tag name) into their own lists or groups?

Advertisement

Answer

You can use the following regex to match any three uppercase letters, followed by anything in parentheses:

JavaScript

Regex101

Use a collections.defaultdict to keep track of all your results. The identifier will be the key for this defaultdict, and the values will be lists containing all the matches for that identifier.

JavaScript

Which gives the following results:

JavaScript

Since you have a fixed set of identifiers, you can replace the [A-Z]{3} portion of the regex with something that will only match your identifiers:

JavaScript

It is also possible to build this regex if you have your identifiers in an iterable:

JavaScript
Advertisement