Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python regular expression doesn't match all letters after "or" group

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading