Python Forum

Full Version: Regex: positive lookbehind
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I am new to Python. I have used regex in Uipath but when I transferred my regex expression to Python it doesn't seem to work. I get error "NoneType object has no attribute 'group'", which mean a match is not found.

But my regex expression works fine in Uipath.

 text_lines=f.readlines()
       model_regex=re.compile(r'(?<=model choice :).*')
       model=model_regex.search('text_lines')
       #print(text_lines)
       print(model.group()) 
1) do I have to place my variable (text_line) in quotation marks here?

model=model_regex.search('text_lines')
2) I basically open a csv file and read it all the text using
text_lines=f.readlines()
But will text_lines look exactly like in the csv file? I noted when I use print text_lines look jumbled up.

3) Is there a way to read in text_lines to look exactly like in the csv files so that my regex expression work?

Thank you
(Sep-19-2020, 10:36 AM)Secret Wrote: [ -> ]Is there a way to read in text_lines to look exactly like in the csv files so that my regex expression work?
Do you want to read the file in line-by-line fashion?
Probably, you don't need to use regexp here at all, e.g.

for line in f:
    index = line.find('model choice :')
    if index > 0
        index += len('model choice :') 
        what_you_need = line[index:]
(Sep-19-2020, 10:36 AM)Secret Wrote: [ -> ]1) do I have to place my variable (text_line) in quotation marks here?
Now is just a string 'text_lines',then this string is all that you search in Wink
readlines() give back a list,and you can not pass a list to a regex search.
Have to loop over readlines() or ''.join() to string.
text_lines = f.readlines()
for line in text_lines:
    # Do regex stuff with line
When loop over many lines in regex can you re.finditer() for only load line bye line in memory,and avoid load the whole list.
Example.
import re

data = '''\
hi model choice : 999
model choice : abc
The green car had a model choice : Red color'''

pattern = re.compile(r"(?<=model choice :).*")
for match in pattern.finditer(data):
    print(match.group().strip())
Output:
999 abc Red color