Skip to content Skip to sidebar Skip to footer

How To Use Regex For Words

I was trying a simple regex code to match the following: line = 'blah black blacksheep blah' if re.match(r'(\bblack\b)', line): print 'found it! What am I doing wrong, I can'

Solution 1:

From the docs:

re.match(pattern, string, flags=0)

If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance.

You probably want to use re.search or re.findall instead.

Solution 2:

You should use re.search or re.findall here:

>>>strs = 'blah black blacksheep blah'>>>re.search(r'\bblack\b', strs).group(0)
'black'

>>>re.findall(r'\bblack\b', strs)
['black']

Solution 3:

You want re.search instead of re.match. From the docs:

7.2.5.3. search() vs. match()

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

Solution 4:

Use re.search() (returns None if no match on the whole string):

line = 'blah black blacksheep blah'if re.search(r'(\bblack\b)', line):
    print'found it!

Post a Comment for "How To Use Regex For Words"