Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Python Regex Find pattern

Tags:

python

regex

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,

Brock

like image 961
Btibert3 Avatar asked Feb 14 '10 04:02

Btibert3


People also ask

How do you search for a regex pattern at the beginning of a string in Python?

re.match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.

How do I search for multiple patterns in Python?

Search multiple words using regex Use | (pipe) operator to specify multiple patterns.


1 Answers

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

like image 113
Alex Martelli Avatar answered Oct 20 '22 23:10

Alex Martelli