Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a word that starts with a specific character

Tags:

python

regex

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?

like image 578
PrimingRyan Avatar asked May 08 '13 12:05

PrimingRyan


4 Answers

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

like image 67
jamylak Avatar answered Oct 13 '22 00:10

jamylak


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']
like image 33
Adem Öztaş Avatar answered Oct 12 '22 23:10

Adem Öztaş


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)
like image 21
Narekzzz Avatar answered Oct 12 '22 22:10

Narekzzz


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

like image 28
user3533685 Avatar answered Oct 12 '22 22:10

user3533685