Robert Jones Robert Jones - 10 months ago 17
Python Question

Is there a way to use regular expressions to match two numbers in any order while exclude other numbers?

I am trying to match numbers that contains the digits 1 and 2 in any order and but that doesn't contain digits 0,3 or 4.

My results should include:


import re

exampleLine = 'prices xom,129,291,201,124,127,261'

regEx = re.findall(r'\d[1+=2][^034]',exampleLine)



You can do it like this:


You need first to use word-boundaries to avoid numbers to be truncated.

Then you can use character classes to be sure that numbers use only allowed digits.

To finish, you must describe the two possible scenarios "the 1 appears first or the 2 appears first" using a non-capturing group and an alternation.

[5-9]* # eventual digits until the first 1 or 2
(?:          # non-capturing group
    1[15-9]*2   # 1 is the first
  |             # OR
    2[25-9]*1   # 2 is the first