[Tutor] Re Module

Alan Gauld alan.gauld at yahoo.co.uk
Thu Dec 27 20:02:10 EST 2018


On 27/12/2018 15:10, Asad wrote:

> file1 - I need a search a error say x if the error matches
> 
> Look for the same error x in other file 2
> 
> Here is the code :
> I have 10 different patterns therefore I used list comprehension and
> compiling the pattern so I loop over and find the exact pattern matching
> 
> re_comp1 = [re.compile(pattern) for pattern in str1]

I assume str1 is actually a list of strings? You don't
show the definition but since you say it gives the
expected output I'll hope that its correct.

> for pat in re_comp1:
>     if pat.search(st,re.IGNORECASE):
>         x = pat.pattern
> print x                ===> here it gives the expected output it correct

I assume st comes from your file1? You don't show us that
bit of code either...

But you do realize that the print only shows the last result.
If there is more than one matching pattern the previous results
get thrown away. And if you only care about one match you
could just use a single regex.
On the other hand, if you do only want the last matching
pattern then what you have works.

> if re.search('x', line, re.IGNORECASE) is not None:  ===> Gives a wrong
> match
>       print line

Notice that you pass the string 'x' into the search.
I assume it is meant to be x? That means you are searching
for the single character 'x' in line. You also don't show
us where line comes from I assume its the other file?

But why do you switch from using the compiled pattern?
Why not just assign x to the pattern object pat? This can
then be used to search line directly and with greater
efficiency.


> if re.search(x, line, re.IGNORECASE) is not None: then no match occurs
>       print line

And are you sure a match should occur?
It would help debug this if you showed us some sample data.
Such as the value of x and the value of line.

Given you are obviously only showing us a selected segment
of your code its hard to be sure. But as written here you
are searching line even if no pattern matches in file1.
That is, you could loop through all your patterns, never
assign anything to x and then go ahead and try to search
for 'x' in line. You should probably check x first.

Also, since you don't show the file looping code we don't
know whether you break out whenever you find a match or
whether the rest of the code is all inside the first
loop over file1. Trying to debug someone else's code
is hard enough. When we only have half the code we are
reduced to guesswork.

Finally, do you get any error messages? If so, please
post them in their entirety. Based on your code I'm
assuming you are working on Python v2.? but its always
worth posting the python version and OS.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list