-1

I have a really simple set of strings:

  • These are the items 17, 28
  • These are the items 9
  • These are the items 5, 8, 207
  • I shouldn't match, but here's an arbitrary number to make things hard 14

I'm trying to create a regex that will give me the digits as a list of items:

r = re.compile(r'These are the items (?:(?P<item_numbers>\d+),?\s*)+')

I thought that wrapping the capturing group I was interested in within a non-capturing group would work, but when I match any string with multiple values (say our 17, 28 example):

input_string = 'These are the items 17, 28'
match = r.match(input_string)
match.groups()
> ('28',)

match.group('item_numbers')
> '28'

Is there a way I can do what I want with a single regex or is this a task not well suited to a regex?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Niko
  • 4,158
  • 9
  • 46
  • 85

1 Answers1

1

findall is probably what you're looking for. Try this out for size:

r = re.compile(r'(?:(?<=\D)|(?<=\A))(\d+)(?=\D|\Z)')
re.findall(r, input_string)
Eric Le Fort
  • 2,571
  • 18
  • 24
  • My question is definitely an unintentional dupe, but this actually works fairly well with some adjustment. Thanks – Niko Nov 26 '19 at 21:07