fork download
  1. import re
  2. text = "1. 1xyz-2xyz - it's OK\n2. 1-2xyz - it's OK\n3. 1xyz - it's OK\n4. 1-2 - there should be no match"
  3. pattern = r"\b([0-9])(xyz)?(?:-([0-9])(xyz)?)?\b(?(2)|(?(4)|(?!)))"
  4. print( [x.group() for x in re.finditer(pattern, text)] )
Success #stdin #stdout 0.03s 9680KB
stdin
Standard input is empty
stdout
['1xyz-2xyz', '1-2xyz', '1xyz']