fork download
  1. import re
  2. s = ['foo 1',
  3. "foo 2 don't capture this text",
  4. '3 foo',
  5. '4 foo capture this text',
  6. 'foo 1 2 3']
  7. pat = r'^(?:(?P<start_number>\d+) (?P<name>.+)|(?P<name2>.*?) ?(?P<end_number>\d+).*)$'
  8. for x in s:
  9. m = re.search(pat, x)
  10. if m and m.group("start_number"):
  11. print("{0}, {1}".format(m.group("start_number"), m.group("name")))
  12. elif m and m.group("end_number"):
  13. print("{0}, {1}".format(m.group("end_number"), m.group("name2")))
Success #stdin #stdout 0.01s 9024KB
stdin
Standard input is empty
stdout
1, foo
2, foo
3, foo
4, foo capture this text
1, foo