I want to sort out words which are started with 's' in sentence by python.
Here is my code:
import re
text = "I was searching my source to make a big desk yesterday."
m = re.findall(r'[s]\w+', text)
print m
But the result of code is :
['searching', 'source', 'sk', 'sterday'].
How do I write a code about regular expression? Or, is there any method to sort out words?
>>> 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+'
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']
I tried this sample of code and I think it does exactly what you want:
import re
text = "I was searching my source to make a big desk yesterday."
m = re.findall (r'\b[s]\w+', text)
print (m)
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With