Search code examples
pythonstringsubstringregex-negation

returns string that does not contain the substring in the list negative regex


I need to create a list or return a non-empty variable that contains characters different from the words that are in the list, I thought of regex, but how do I do it?? Bellow, I show an example.

Example 1:

lista_ok = ['EXECUCAO OK','EXECUÇÃO OK',' Nº da Apólice já cadastrada']

x = " ['EXECUCAO OK', ' Não existe a apólice informada'] " # (string)

Output: ' Não existe a apólice informada'

Example 2:

x = " [Nº da Apólice já cadastrada', 'EXECUCAO OK', ' Não existe a apólice informada'] " # (string)

Output: ' Não existe a apólice informada'

Example 3:

x = " ['EXECUCAO OK'] " or "[Nº da Apólice já cadastrada']" or "['EXECUCAO OK',' Nº da Apólice já cadastrada']" # (string)

Output: Empty or " "


Solution

  • Use ast.litera_eval to transform x to a python list, then keep the words not in lista_ok

    def main(values_ok, value):
        words = ast.literal_eval(value)
        return " ".join([word for word in words if word not in values_ok])
    
    
    lista_ok = ['EXECUCAO OK', 'EXECUÇÃO OK', ' Nº da Apólice já cadastrada']
    
    print(main(lista_ok, " ['EXECUCAO OK', ' Não existe a apólice informada'] "))
    #  Não existe a apólice informada
    print(main(lista_ok, " [' Nº da Apólice já cadastrada', 'EXECUCAO OK', ' Não existe a apólice informada'] "))
    #  Não existe a apólice informada
    print(main(lista_ok, " ['EXECUCAO OK'] "))
    print(main(lista_ok, "[' Nº da Apólice já cadastrada']"))
    print(main(lista_ok, "['EXECUCAO OK',' Nº da Apólice já cadastrada']"))
    

    To get a list of words :

    return [word for word in words if word not in values_ok]
    

    To get a string of them

    return " ".join([word for word in words if word not in values_ok])