Farrell32
Farrell32

Reputation: 7

Python - Regex no group is found

How do I add a group to my regex?

Here is my regex: (?<=code )(\d+)

Here is my code:

rsize= re.compile(r'(?<=code )(\d+)')
code = rsize.search(codeblock).group("code")

How come when I run the code I get the error: IndexError: no such group ? How do I write this regex to create a group named code?

EDIT I read the responses, but, my question is, how exactly do I append that to my regex?

Upvotes: 0

Views: 1124

Answers (2)

Amber
Amber

Reputation: 526583

A named group in Python's re syntax is defined as (?P<name>...) where name is the name of the group and ... is the pattern the group matches.

So if your goal is to create a named group 'code' that matches a set of digits, you'd want:

(?P<code>\d+)

Upvotes: 0

alecxe
alecxe

Reputation: 473853

The "named group" syntax is a little bit different:

(?P<name>group)

Example:

>>> import re
>>>
>>> s = "1234 extract the numbers"
>>> pattern = re.compile(r'(?P<code>\d+)')
>>> pattern.search(s).group("code")
'1234'

Upvotes: 1

Related Questions