Python (Scripting) - Find matching expression using re.match

by
Jeremy Canfield |
Updated: January 24 2024
| Python (Scripting) articles
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).
find and re.match can be used to determine if a string or integer does or does not contain a matching expression.
In this example, re.match should evaulate to true because the foo variable does contain "Hello".
#!/usr/bin/python
import re
foo = "Hello World"
if re.match('.*Hello.*', foo, re.IGNORECASE):
print("It's a match. The foo variable contains Hello")
Or like this, 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 contain 'Hello'")
else:
print("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 contain 'Hello' or 'World'")
else:
print("The foo variable contains 'Hello' or 'World'")
And here is how you would combine two or more re.match.
#!/usr/bin/python
import re
foo = "Hello World"
if not re.match('.*Hello.*', foo, re.IGNORECASE) and re.match('.*World.*', foo, re.IGNORECASE):
print("The foo variable contains 'Hello' and 'World'")
else:
print("The foo variable does NOT contain 'Hello' and 'World'")
Did you find this article helpful?
If so, consider buying me a coffee over at