How to find a word that starts with a specific character
If you want to match a single character, you don't need to put it in a character class, so
s
is the same than[s]
.What you want to find is a word boundary. A word boundary
\b
is an anchor that matches on a change from a non word character (\W
) to a word character (\w
) or vice versa.
The solution is:
\bs\w+
this regex will match on a s
with not a word character before (works also on the start of the string) and needs at least one word character after it. \w+
is matching all word characters it can find, so no need for a \b
at the end.
See it here on Regexr
>>> import re
>>> text = "I was searching my source to make a big desk yesterday."
>>> re.findall(r'\bs\w+', text)
['searching', 'source']
For lowercase and uppercase s
use: r'\b[sS]\w+'
Lambda style:
text = 'I was searching my source to make a big desk yesterday.'
list(filter(lambda word: word[0]=='s', text.split()))
Output:
['searching', 'source']
I know it is not a regex solution, but you can use startswith
>>> text="I was searching my source to make a big desk yesterday."
>>> [ t for t in text.split() if t.startswith('s') ]
['searching', 'source']