1

I came across the website rubular.com, and their example regex was :

(?<month>\d{1,2})\/(?<day>\d{1,2})\/(?<year>\d{4})

where the months, day, and year encased in the < > tags each group with that name.

I'm wondering if there's a way to do that in Python since I couldn't find it in the documentation.

3 Answers 3

2

You do that using (?P<group_name>...):

(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<year>\d{4})

See documentation

Sign up to request clarification or add additional context in comments.

Comments

2

To do so in Python, you would prefix the named group with the letter 'P' like so:

import re

match = re.search('(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<year>\d{4})', '01/02/2000')

print match.group('day')
print match.group('month')
print match.group('year')

The documentation page for Regex doesn't clearly highlight it, but you are looking for the section on

(?P<name>...)

Comments

0

You can use this:

(?P<month>\d{1,2})\/(?P<day>\d{1,2})\/(?P<year>\d{4})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.