RNK
RNK

Reputation: 141

Regular expressions in python (multiple variables)

I have an array of strings that I want to match in python. Is there a way to do this without using for loops?

All the examples I have seen so far are like the following, where you have to loop through each element to find a match:

import re

patterns = [ 'this', 'that' ]
text = 'Does this text match the pattern?'

for pattern in patterns:
    print 'Looking for "%s" in "%s" ->' % (pattern, text),

    if re.search(pattern,  text):
        print 'found a match!'
    else:
        print 'no match'

Would it be possible to do this without using a for loop

Upvotes: 1

Views: 3385

Answers (4)

hariK
hariK

Reputation: 3059

import re

patterns = [ 'this', 'that' ]

text = 'Does this text match the pattern?'

def pattern_checker(patterns):

    pattern = iter(patterns)
    if re.search(next(pattern),  text):
            print 'found a match!'
            pattern_checker(pop_patterns(patterns))
    else:
            print 'no match'
            pattern_checker(pop_patterns(patterns))

def pop_patterns(patterns):

    if len(patterns) > 0:
            del patterns[0]
            return patterns
    else:
            return 0

try:

    pattern_checker(patterns)

except Exception, e:

    pass

Upvotes: 0

pgy
pgy

Reputation: 311

Not exactly the same as your for loop, but concatenate the patterns with a |. a|b matches if either a or b matches.

ultimate_pattern = '|'.join(patterns)

If you want to get all matches, use findall, but this way it cannot be known which original pattern triggered the match for it returns a list of strings.

re.findall(ultimate_pattern, text)

Upvotes: 3

ChrisH
ChrisH

Reputation: 15

Could you use a while loop like so?

patterns = [ 'this', 'that' ]
text = 'Does this text match the pattern?'
test = True
position = 0

while test == True:
  if patterns[position] in text:
      print(patterns[position],'is in the text')

  else:
      print (patterns[position],'is not in text')

  position = position+1
  if position >= len(patterns):
      test = False

Upvotes: 0

user2555451
user2555451

Reputation:

Perhaps you are looking for something like this:

import re

patterns = [ 'this', 'that' ]
text = 'Does this text match the pattern?'

if any(re.search(x, text) for x in patterns):
    print 'found a match!'
else:
    print 'no match'

It uses any and a generator expression to test every pattern in patterns against text. As an added bonus, the solution uses lazy evaluation and will only test as many patterns as is necessary.

Upvotes: 0

Related Questions