There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).
There are a few Python modules that can be used to determine if a string or integer does or does not contain a matching expression.
- find - returns the first matching patterns anywhere in a string or integer
- re.findall - returns a list containing all of the matching patterns anywhere in a string or integer
- re.match (this article) - evaluates to true if there is a single match of a pattern at the beginning of a string or integer
- re.search - evaluates to true if there is a single match of a pattern anywhere in a string or integer
re.match checks for a match at the very beginning of a string or integer. If the pattern is not found at the beginning of the string or integer, re.match will return None. In this way, re.match is similar to the ^ regular expression, checking for a match at the beginning of the string or integer.
In this example, re.match should evaluate to true because the foo variable begins with "Hello".
#!/usr/bin/python
import re
foo = "Hello World"
if re.match('.*Hello.*', foo, re.IGNORECASE):
print("It's a match. The foo variable begins with Hello")
Or like this, to determine if a string or integer does not begin with a pattern using not re.match.
#!/usr/bin/python
import re
foo = "Hello World"
if not re.match('.*Hello.*', foo, re.IGNORECASE):
print("The foo variable does NOT begin with 'Hello'")
You can use the .* regular expression with re.match to search for any occurrence of the pattern in the string or integer.
#!/usr/bin/python
import re
foo = "Well Hello World"
if re.match('.*Hello.*', foo, re.IGNORECASE):
print("It's a match. The foo variable contains Hello")
But in this scenario, it almost always makes sense to instead use re.search, because re.search check for a match anywhere in the string or integer.
#!/usr/bin/python
import re
foo = "Well Hello World"
if re.search('.*Hello.*', foo, re.IGNORECASE):
print("It's a match. The foo variable contains Hello")
Here is how to evaluate two (or more) expressions. This is an or clause, where the expression will evaluate to true if the foo variable contains Hello or World.
#!/usr/bin/python
import re
foo = "Hello World"
if not re.match('(Hello|World)', foo, re.IGNORECASE):
print("The foo variable does NOT begin with 'Hello' or 'World'")
Did you find this article helpful?
If so, consider buying me a coffee over at 