Skip to content

Try fixing regex incompatibility#1067

Closed
goodspark wants to merge 1 commit intoscrapinghub:masterfrom
goodspark:patch-1
Closed

Try fixing regex incompatibility#1067
goodspark wants to merge 1 commit intoscrapinghub:masterfrom
goodspark:patch-1

Conversation

@goodspark
Copy link
Copy Markdown

@goodspark goodspark commented Aug 11, 2022

Fixes #1045

Based on #1045 (comment)

@Gallaecio
Copy link
Copy Markdown
Contributor

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

@DJRHails
Copy link
Copy Markdown
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
Copy Markdown
Contributor

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
Copy Markdown
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