Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

groupdict() returns only first character of the match if there is a single named capture group #25

Open
simonw opened this issue Jul 20, 2022 · 2 comments

Comments

@simonw
Copy link

simonw commented Jul 20, 2022

This line:

[m.groupdict() for m in rure.compile('(?P<word>\w+)').finditer("hello there")]

Returns this:

[{'word': 'h'}, {'word': 't'}]

I would expect it to return this:

[{'word': 'hello'}, {'word': 'there'}]

Adding a second named group fixes this issue for some reason:

[m.groupdict() for m in rure.compile('(?P<name>\w+)(?P<nomatch>)').finditer("hello there")]

Returns:

[{'name': 'hello', 'nomatch': ''}, {'name': 'there', 'nomatch': ''}]
@simonw
Copy link
Author

simonw commented Jul 20, 2022

I think the bug may be in this code:

rure-python/rure/regex.py

Lines 235 to 251 in 024bf4b

def groupdict(self, default=None, decode=True):
group_indices = sorted(self.re.groupindex.values())
group_data = self.group(*[i for i in group_indices], default=default)
gdict = {}
for pos, g_name_index in enumerate(
sorted(self.re.groupindex.items(),
# Sort by value
key=lambda x: x[1])):
gname = g_name_index[0]
gval = group_data[pos]
if decode:
if isinstance(gname, bytes):
gname = gname.decode('utf8')
if isinstance(gval, bytes):
gval = gval.decode('utf8')
gdict[gname] = gval
return gdict

@simonw simonw changed the title finderiter() then groupdict() returns only first character of the match groupdict() returns only first character of the match if there is a single named capture group Jul 20, 2022
@simonw
Copy link
Author

simonw commented Jul 20, 2022

This happens without .finditer() too:

>>> rure.compile('(?P<name>\w+)').match("hello").groupdict()
{'name': 'h'}
>>> rure.compile('(?P<name>\w+)(?P<nomatch>)').match("hello").groupdict()
{'name': 'hello', 'nomatch': ''}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant