1

I have been running into a problem with python's re module.

This is the simplest version of the issue

import re

print re.findall('a|ab','aab')      # ['a', 'a']
print re.findall('ab|a','aab')      # ['a', 'ab']

I generate regexes at runtime from a text file and cannot be certain that they will be in the correct order. Is there any way around this issue?

2
  • he wants the second result(I think at least)... Commented Jul 9, 2012 at 19:02
  • Yes, I want the 'ab' in this example. Commented Jul 9, 2012 at 19:05

1 Answer 1

2

sort them by size... longer first

eg:

s_regs = sorted(regexes,key=lambda x:len(x))
s_regs.reverse()
regex = '|'.join(s_regs)
Sign up to request clarification or add additional context in comments.

2 Comments

The same but slightly more efficient regex = '|'.join(sorted(regexes, key=len, reverse=True))
I would also use re.escape for every regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.