user1881957
user1881957

Reputation: 3378

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

I know it's a Regular Expression. I have seen this particular regular expression in a piece of code. What does it do? Thanks

Upvotes: 31

Views: 140205

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174624

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',)

Upvotes: 45

Ry-
Ry-

Reputation: 224906

It matches one or more digits followed by a slash followed by one or more digits.

The two "one or more digits" here also form groups, which can be extracted and used.

Upvotes: 11

Related Questions