Baz
Baz

Reputation: 13125

Switching on regex matches

Can you suggest a nicer way to write the following:

for r in replacements:

    m = pattern_1.match(r)
    if m:
        a.append((r,m.group(1),m.group(2),m.group(3)))
        continue

    m = pattern_2.match(r)
    if m:
        b.append((r,m.group(1),m.group(2),m.group(3)))
        continue

    if "import" in r:
        c.append(r)
    else:
        d.append(r)

I tried "if pattern_1.match(r) as m:" but got an invalid syntax error. Is this a future feature? I'm using 2.6.

Upvotes: 1

Views: 39

Answers (1)

John Zwinck
John Zwinck

Reputation: 249123

for r in replacements:
  for pattern, dest in zip([pattern_1, pattern_2], [a, b]):
    m = pattern.match(r)
    if m:
        dest.append((r,m.group(1),m.group(2),m.group(3)))
        break
  else:
    (c if "import" in r else d).append(r)

Upvotes: 2

Related Questions