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