04.12.19 18:05, Guido van Rossum пише:
On Wed, Dec 4, 2019 at 12:34 AM Serhiy Storchaka
<storch...@gmail.com
<mailto:storch...@gmail.com>> wrote:
`next(re.finditer(...), None)` is a weird way of writing
`re.search(...)`.
`next(re.finditer(...), defaults)` is the same as `re.search(...) or
defaults`.
Not so fast. re.search() returns a Match object, while re.finditer() and
re.findall() return strings. For people who are just interested in
strings, the Match object is just a distraction.
re.finditer() yields Match objects. re.findall() returns a list of
strings or tuples. re.finditer() is more fundamental, re.findall() can
be implemented using re.finditer():
def findall(pattern, string):
p = re.compile(pattern)
result = []
for m in p.finditer(string):
if p.groups == 0:
result.append(p.group(0))
elif p.groups == 1:
result.append(p.group(1))
else:
result.append(p.groups())
return result
I suppose re.findall() is an older interface.
On other hand, re.finditer() is roughly equivalent to the following code:
def finditer(pattern, string):
p = re.compile(pattern)
pos = 0
while True:
m = p.search(string, pos=pos)
if m is None:
break
yield m
pos = m.end()
Actually it is a little more complex because of handling zero-width
matches. Currently re.search() does not support required option, so in
real finditer() cannot be implemented in Python using only search(). But
this is irrelevant to the first item, `next(re.finditer(...), None)` is
always equal to `re.search(...)`.
> I think I am +1 on
> adding re.findfirst() as proposed by the OP.
It is not clear what it should return. A Match object, a string, a
tuple, whatever? What should it return if no match found -- None, en
empty string, an empty tuple, error? I suppose that different users can
have different need. It is not practical to provide functions for all
combinations, it is easy to write a function for your needs using
re.search(). We can only add some receipts in the documentation.
The concrete user code can be a little bit simpler (one-liner) if we
provide an empty match object. For example:
(re.search(patter.string) or EmptyMatch).groups()
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/PRRLZTLCRWTMY7HBSLRQL32NQ2ENOMLK/
Code of Conduct: http://python.org/psf/codeofconduct/