Simple Python Regex Find pattern


I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the little I know, this sounds like a Regex question.

What is the pattern match code that will let me find all words that match my pattern?

Many thanks in advance,


2/14/2010 4:08:53 AM

Accepted Answer

import re
print re.findall(r'\bv\w+', thesentence)

will print every word in the sentence that starts with 'v', for example.

Using the split method of strings, as another answer suggests, would not identify words, but space-separated chunks that may include punctuation. This re-based solution does identify words (letters and digits, net of punctuation).

2/14/2010 4:13:10 AM

I second the Dive Into Python recommendation. But it's basically:

m = re.findall(r'\bf.*?\b', 'a fast and friendly dog')

\b means word boundary, and .*? ensures we store the whole word, but back off to avoid going too far (technically, ? is called a lazy operator).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow