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

Try fixing regex incompatibility #1067

Closed
wants to merge 1 commit into from

Conversation

goodspark
Copy link

@goodspark goodspark commented Aug 11, 2022

Fixes #1045

Based on #1045 (comment)

@Gallaecio
Copy link
Member

Why is DIGIT_GROUP_PATTERN replaced by pattern? Isn’t that a change in behavior?

@DJRHails
Copy link
Contributor

DJRHails commented Nov 8, 2022

Can confirm this has no change in behaviour (and should be merged). The aim of this code is to wrap digits with named groups. The desired behaviour is preserved as:
(\\d+[.,]?\\d*) days ago should be translated into (?P<n>\\d+[.,]?\\d*) days ago

The current breakage is due to some extra escaping being desired by re.sub.

Currently the code uses re.sub to do a replacement of \\d+ -> ?P<n>\\d+ (or equivalently in raw strings r'\d+' -> r'?P<n>\d+'. It uses the regex DIGIT_GROUP_PATTERN = r'\\d\+' (a literal \\d+ eventually)

For some reason, that still escapes me, re.sub now requires an additional set of escapes:

# Fix 1: sub with triple escape
DIGIT_GROUP_PATTERN.sub('?P<n>\\\\d+', pattern) # => (?P<n>\\d+[.,]?\\d*) days ago

# Fix 2: sub with raw double escape
DIGIT_GROUP_PATTERN.sub(r'?P<n>\\d+', pattern) # => (?P<n>\\d+[.,]?\\d*) days ago

# Fix 3 (as in this PR): ditch sub and do it using builtins
pattern.replace('\\d+', '?P<n>\\d+') # => (?P<n>\\d+[.,]?\\d*) days ago

It might also be wise to expand the pattern slightly to:

pattern.replace('(\\d+', '(?P<n>\\d+')

as if anyone adds a \d+ in the text instead of a \d* everything will break

@Gallaecio
Copy link
Member

Makes sense.

However:

  • DIGIT_GROUP_PATTERN does not seem used anymore, so we should remove it.
  • pattern.replace('(\\d+', '(?P<n>\\d+') indeed sounds better. However, seeing how the old code did it without it, I am OK with not improving on this.

@DJRHails
Copy link
Contributor

Made those changes #1095 here 👍

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

Successfully merging this pull request may close these issues.

Bad escape characters trigger an exception
3 participants