Search code examples
pythonpython-3.xregexpython-re

Match several changeable arguments


I want to see that here :

[AA] - ( 371M 39F - COMPLETE ) - [AA]

but it always changes, for example it can be like this here

[AA] - ( 371M 39F - COMPLETE ) - [AA]
[cc] - ( 3M 3F - COMPLETE ) - [cc]
[1234] - ( 99.9M 111F - COMPLETE ) - [1234]
[A55bg] - ( 45571M 31239F - COMPLETE ) - [A55bg]

It always starts with [ and ends with ]

the following is always the same

[ ] - (  M  F - COMPLETE ) - [ ]

I would like to use the variable 'skip' to check whether it appears in the list.

import re

list = ['/home', '/home/test1', '/home/test1/aaa', '/home/test1/aaa/[AA] - ( 371M 39F - COMPLETE ) - [AA]', 'ccc']
skip = '\[([0-9|a-z|A-Z]+)\]\s+\-\s+\(\s+(\d+\.*\d*)M\s+(\d+)F\s+\-\s+COMPLETE\s+\)\s+\-\s+\[([0-9|a-z|A-Z]+)\]$'

for element in list:
    m = re.search(skip, element)
    if m:
        print('match')

Solution

  • Assuming the characters strings noted by zz are alphanumeric only, you could use a Regex pattern like the following. It will emit a match group for each of the zz in the output list for your further use.

    \[([0-9a-zA-Z]+)\]\s+\-\s+\(\s+(\d+\.*\d*)M\s+(\d+)F\s+\-\s+COMPLETE\s+\)\s+\-\s+\[([0-9a-zA-Z]+)\]
    

    This does allow for any length of each zz 1 or longer, as well as multiple whitespaces wherever one appears. If you need to constrain it further, edit away!