-1

I'm trying to match FD or MD in a string by doing:

matches = re.findall(r"(F|M)D",myString)

Suppose myString = 'MD'. Then, matches becomes

matches = ['M']

Why does it ignore D?

sodiumnitrate
  • 2,899
  • 6
  • 30
  • 49

1 Answers1

0

That's because (F|M) is a group, and D is not a part of this group.

Use this instead:

matches = re.findall(r"((?:F|M)D)",myString)

For a visual representation of the differences between these two patterns, I really like to use Regexper.com:

The Python documentation on regular expressions has a lot more information available here.

Note that ?: indicates that F|M is a "non-capturing" group. If the pattern were ((F|M)D) instead, then matches would be [('MD', 'M')] (which doesn't sound like what you want).

Donut
  • 110,061
  • 20
  • 134
  • 146