python中的正则表达式(多个变量)

时间:2014-12-12 00:35:08

标签: python regex

我有一个我希望在python中匹配的字符串数组。有没有办法在不使用for循环的情况下执行此操作?

到目前为止我看到的所有示例都如下所示,您必须遍历每个元素才能找到匹配项:

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'

是否可以在不使用for循环的情况下执行此操作

4 个答案:

答案 0 :(得分:2)

与for循环不完全相同,但将模式与|连接起来。如果a|ba匹配,则会b匹配。

ultimate_pattern = '|'.join(patterns)

如果你想获得所有匹配,请使用findall,但这样就无法知道哪个原始模式触发了匹配,因为它返回一个字符串列表。

re.findall(ultimate_pattern, text)

答案 1 :(得分:0)

也许你正在寻找这样的东西:

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'

它使用anygenerator expression来测试patterns中针对text的每个模式。作为额外的奖励,该解决方案使用延迟评估,并且只测试尽可能多的模式。

答案 2 :(得分:0)

你可以像这样使用while循环吗?

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

答案 3 :(得分:0)

导入重新

patterns = [' this',' that' ]

text ='此文字是否与模式匹配?'

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

尝试:

    pattern_checker(patterns)

除了例外,e:

    pass
相关问题