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

regex to find word that starts with c and ends with o

I am trying to write some code to find sentence that has any word that has a letter c followed by a another letter and ends in o. e.g. cxo, ceo, cfo
Aplogies should have mentioned that it can only have one letter in the middle of c and o

I’ve tried

("c.o")

but this does not seem to work. Please give me some help on where I am going wrong

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

Some examples.

["chrome", "commo", "cron"] – These should not show

["cxo", "cfo", "coo", "cho"] – These should show

>Solution :

If your goal is to find any 3-letter word starting with C and ending with O, you can insert a word boundary \b before and after your match like so: /\bc\wo\b/. The presence of \b will prevent partial matches like echo from matching your regex, but will still allow for matches to occur at the beginning and end of your match string.

As an example with python:

import re
r = re.compile(r"\bc\wo\b")
print(r.search("at the end a ceo"))       # => match
print(r.search("ceo at the start"))       # => match
print(r.search("in the middle a ceo is")) # => match
print(r.search("fooceobar"))              # => no match
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