1

Regular Expressions: Search in list

filter(r.match, list)

in this post there is r.match, what is r.match.

my understanding is that r stands for re.compile() and return a Pattern. but dig into https://docs.python.org/3/library/re.html#re.compile, there is only Pattern.match()method? no pattern.match..

tripleee
  • 175,061
  • 34
  • 275
  • 318
chenmo
  • 13
  • 3

2 Answers2

0

No, r is a compiled pattern from earlier in the code. Something like

import re
r = re.compile(r'hello')
tripleee
  • 175,061
  • 34
  • 275
  • 318
0

r is the variable, which is a pattern.

As you can see in the second answer, it is assigned to:

r = re.compile(".*cat")

The reason there is not parenthesis is because it's using the filter function which automatically adds the parenthesis and adds the element in the list to filter.

As mentioned in the docs:

Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

As you can see, it is the same as a generator with having parenthesis. The filter function doesn't need parenthesis, that's the specialty of it.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114