You are viewing a single comment's thread from:

RE: Quick Python Regex Tip: Return True or False from a Python Regex Match

in #python7 years ago (edited)

Hey good tip! I didn't know the regex boundaries "\b" which match spaces and also start and end of strings. With it we can find by example the apparition of whole words :) great!

Some Tips:


Validating None: If you want to be sure that by example, a function returned something different than None you can do:

if awesome_function_here() is not None:
    print('The function returned something!')

That is useful because python maps number 0 and almost any empty sequence (like `{}, [], (,)`) to False, and sometimes we need to make something if a function returns anything than None :)

Getting all matched strings in regex: If you want to extract all matching sub-strings from a text using regex you can do it like this:
import re

#get all words containing "man"
matching_words = re.findall(r"\b([A-Za-z]*man)\b", "Superman Wolverine Aquaman")
print(matching_words)
# it returns ['Superman', 'Aquaman']

The parentheses let us specify what we want to "extract" from the matched sub-strings.

I will be sharing Python tips too, see you soon =)

@zerocoolrocker