What is (\d+)/(\d+) in regex?

Expanding on minitech’s answer:

  • ( start a capture group
  • \d a shorthand character class, which matches all numbers; it is the same as [0-9]
  • + one or more of the expression
  • ) end a capture group
  • / a literal forward slash

Here is an example:

>>> import re
>>> exp = re.compile('(\d+)/(\d+)')
>>> foo = re.match(exp,'1234/5678')
>>> foo.groups()
('1234', '5678')

If you remove the brackets (), the expression will still match, but you’ll only capture one set:

>>> foo = re.match('\d+/(\d+)','1234/5678')
>>> foo.groups()
('5678',)

Leave a Comment

tech