Regular Expressions in python

Asked

Viewed 143 times

0

How can I read a python file looking for words that fit into a regular expression, for example: search dates(dd/mm/yyyy)?

  • Related: https://answall.com/q/3660/112052 (enough to exchange the \. for / in the regex there accepted answer

1 answer

3

You can do this by implementing a generator that makes use of the library re searching each line of the file for all the words that satisfy the pattern defined by the expression. An outline of this function would be:

def get_pattern_from_file(filename, expression):
  pattern = re.compile(expression)
  with open(filename) as stream:
    for line in stream:
      yield re.findall(pattern, line)

See working on Repl.it

So you can iterate over the function return and get a list of all words that satisfy the line expression. You can even convert the result to just one list, with all the words, using the function itertools.chain.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.