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

Unable to extract words which doesnt start with character c using regular expression

I have a string containing multiple lines with words, and I want to extract all words from the string except those that start with c.

I tried this

import re
inp='''bat
cat
mat
'''
pt=re.compile(r'[^c][a-z]+')
ma=pt.findall(inp)

I’m getting

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

['bat', '\ncat', '\nmat']

This works perfectly fine if I explicitly mention ‘at’

pt=re.compile(r'[^c]at')

Output for this is:

['bat', 'mat']

But it doesn’t work using pt=re.compile(r'[^c][a-z]+')

>Solution :

import re
inp='''bat
cat
map
'''
pt=re.compile(r'\b[^\nc][a-z]+')
ma=pt.findall(inp)
print(ma)

Output:

['bat', 'map']
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