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

Make quantifiers non-greedy #16

Merged
merged 1 commit into from Jul 22, 2019
Merged

Conversation

manycoding
Copy link
Contributor

I don't think there will be any noticeable difference in the real world, but it's still the right way to write regex.
https://docs.python.org/3/howto/regex.html#greedy-versus-non-greedy
Greedy

%timeit re.search(r"""(\d[\d\s.,]*)\s*?(?:[^%\d]|$)""", "90 728.00 руб 103 100.00 руб", re.VERBOSE).group(1)
1.97 µs ± 200 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Non-greedy

%timeit re.search(r"""(\d[\d\s.,]*)\s*(?:[^%\d]|$)""", "90 728.00 руб 103 100.00 руб", re.VERBOSE).group(1)
1.86 µs ± 103 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

[\d\s.,]*\d # number, probably with thousand separators
\s*€\s* # euro, probably separated by whitespace
[\d\s.,]*?\d # number, probably with thousand separators
\s*?€\s*? # euro, probably separated by whitespace
\d\d
(?:$|[^\d]) # something which is not a digit
""", price, re.VERBOSE)
if m:
return m.group(0).replace(' ', '')
m = re.search(r"""
(\d[\d\s.,]*) # number, probably with thousand separators
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one is made greedy on purpose.

@codecov
Copy link

codecov bot commented Jul 18, 2019

Codecov Report

Merging #16 into master will not change coverage.
The diff coverage is n/a.

@@          Coverage Diff          @@
##           master    #16   +/-   ##
=====================================
  Coverage     100%   100%           
=====================================
  Files           3      3           
  Lines          93     93           
  Branches       21     21           
=====================================
  Hits           93     93
Impacted Files Coverage Δ
price_parser/parser.py 100% <ø> (ø) ⬆️

@kmike kmike merged commit 62d11a3 into scrapinghub:master Jul 22, 2019
@kmike
Copy link
Member

kmike commented Jul 22, 2019

Looks good, thanks @manycoding!

@manycoding manycoding deleted the non_greedy branch July 22, 2019 08:27
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.

None yet

2 participants