Kent Johnson wrote:

Just join the individual strings together with | to make a single regex, then search each line for a match:

 >>> import re
 >>> lista = ['hello','goodbye','bubblegum']
 >>> regex = re.compile('|'.join(lista))
 >>> lines = '''line1: blah blah aldkfslfjlajf hello
 ... line2: blah blah dkajfldjfjkdsfalj zippo
 ... line3: blah blah lkdsjalkfjkj bubblegum
 ... line4: blah blah skdjflsdjlkj ditto'''
 >>> lines = lines.split('\n')
 >>> for line in lines:
 ...   if not regex.search(line):
 ...     print line
 ...
line2: blah blah dkajfldjfjkdsfalj zippo
line4: blah blah skdjflsdjlkj ditto
 >>>

Kent

Tzu-Ming Chern wrote:

Hi Python Tutors,

Is there a more elegant solution to matching multiple regular expressions?
An example would be:


lista = ['hello','goodbye','bubblegum'] # lista would contain my regular
expressions I want to match


My file would look something like this:

line1: blah blah aldkfslfjlajf hello
line2: blah blah dkajfldjfjkdsfalj zippo
line3: blah blah lkdsjalkfjkj bubblegum
line4: blah blah skdjflsdjlkj ditto

What I want to do is to only print out those lines that don't contain
those patterns included in lista. So that would be lines 2 and 4.
Any suggestions?

cheers,
tzuming



_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor


There's also a non-re way available:

>>> lista = ['hello','goodbye','bubblegum']
>>> line1 = "blah blah aldkfslfjlajf hello"
>>> line2 = "blah blah dkajfldjfjkdsfalj zippo"
>>> line3 = "blah blah lkdsjalkfjkj bubblegum"
>>> line4 = "blah blah skdjflsdjlkj ditto"
>>> filea = [line1, line2, line3, line4]
>>> for line in filea:
   pflag = True
   for entry in lista:
       if entry in line:
           pflag = False
           break
   if pflag:
       print line

blah blah dkajfldjfjkdsfalj zippo
blah blah skdjflsdjlkj ditto



-- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it.

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to