Regex in Find () function in python

4

I need to use a regex in the Find() function in Python for example, if I use within a loop :

arq = open("arquivo.txt","rb")
var = arq.readline()        
a = var.find("abc.*def")

It will be looking at the line "abc something (. *) def" on all lines of the file, beauty

Now, I have two variables containing a string each, I need to call the function Find() with "Var1. * Var2", ie look for Var1 + anything + Var2

Var1 = "abc"
Var2 = "def"
arq = open("arquivo.txt","rb")
var = arq.readline() 

a = var.find(Var1 ".*" Var2) //DESSA FORMA NÃO FUNCIONA

Can anyone help me with how can I do this type of search on the line containing regex?

    
asked by anonymous 19.12.2016 / 19:19

1 answer

2

With the find() function, you can not do this, but you can do the following:

import re
var1 = "abc"
var2 = "def"
var = 'abc1dois3quatro5def' # aqui e o conteudo do teu ficheiro, arq.readline() 
match = re.compile('{}(.*?){}'.format(var1, var2)).search(var)
if match is not None:
    print(match.group(1)) # 1dois3quatro5
else:
    print('nada encontrado em {}'.format(var))

DEMONSTRATION

From what I noticed in the commented conversation you are using python 2.6, so do this:

import re
var1 = "abc"
var2 = "def"
var = 'abc1dois3quatro5def'
match = re.compile('%s(.*?)%s' % (var1, var2)).search(var)
if match is not None:
    print match.group(0) # abc1dois3quatro5def
else:
    print 'nada encontrado em ' +var
    
19.12.2016 / 19:49