Regex in python Find() function

Asked

Viewed 490 times

4

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

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

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

Only now I have two variables containing one string each, I need to call the function Find() with "Var1 . * Var2", i.e., search 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

Could someone help me how I can do this kind of search on the line containing regex?

1 answer

2


With the function find() I can’t, but here’s what you can do:

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

As far as I can tell, you’re using python 2.6, so go like 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
  • I got the following return: match = re.Compile('{}(.*?){}'.format(var1, var2)). search(var) Valueerror: zero length field name in format, using its code.

  • I already know the problem, I think you are using python 2.6 or below @Mauríciosalin , I will add a solution for you

  • My version is 2.6.6 maybe this is the problem, I am not allowed to update, if it is a code in corporate environment.

  • No problem, we’ll make it work

  • @Mauríciosalin, test this one: http://ideone.com/F4FsWr

  • It worked, however you realize that this removing var1 and var2, I need exactly this only that on the contrary, I need to find the line that has var1 . * var2 and print it.

  • Ha ok then put on "...match.group(0)" @Mauritosalin , or pay only 1 and leave it empty. It’s solved (;

  • Let’s assume that I have a line "pqrstuvxz" and another line "abc1234556def", I need to check the two lines but print only the one that has abc. *def

  • That’s right, I had already put . group(0), it was only to make clear, if someone needs the same solution in the future, thanks @Miguel

  • we had a second problem, when printing match.group(0) theoretically it was to print the whole line, but only imprinting until the second variable

  • Ha ok, so you’d better put a new question @Mauríciosalin , because here I can’t answer that which is completely different from this question... I’m working on a solution to help you

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.