-2

This code snippet is not showing 'bats' & moreover 'eats' is showing as 'eat' in the last? When I don't use '[force]' 7 'at' is showing? What is the use of 'force'?

t="A fat cat doesn't eat oat but a rat eats bats."
mo = re.findall("[force]at", t)
print(mo)
['fat', 'cat', 'eat', 'oat', 'rat', 'eat']
Matt Joy
  • 3
  • 4

3 Answers3

1

One of places where you can find explanation of Python regular expressions is re module docs, in your case - [force]at relevant part is that [] is

Used to indicate a set of characters. In a set:

Characters can be listed individually, e.g. [amk] will match 'a', 'm', or 'k'.

Therefore [force]at will match: fat, oat, rat, cat, eat.

Daweo
  • 10,139
  • 2
  • 5
  • 10
0

you can use:

import re
t="A fat cat doesn't eat oat but a rat eats bats."
mo = re.findall("\w*at\w*", t)
print(mo)

output:

['fat', 'cat', 'eat', 'oat', 'rat', 'eats', 'bats']

\w* matches any word character (equal to [a-zA-Z0-9_])

* Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

[force]at

Match a single character present in the list below [force] force matches a single character in the list force (case sensitive) at matches the characters at literally (case sensitive)

ncica
  • 6,018
  • 1
  • 12
  • 30
0

Play around with regex here. There you have an explanation for your whole regex you use. I.e. comare it to [fc]at to get a feeling for it.

Manuel
  • 526
  • 3
  • 8