In python, we can use python re.match() to check a string starting with a pattern or not. In this tutorial, we will use some examples to show you how to use this function.
re.match()
re.match() is defined as:
re.match(pattern, string, flags=0)
Here pattern is a string or regular expression. It will check string starting with pattern or not. Here is an exmaple:
import re text = 'a456abc123' result = re.match('b', text) print(type(result)) print(result) if result: print(result.group(0))
Here character b is in text. Run this code, you will get this reuslt:
<class 'NoneType'> None
result is None, which means text is not started with ‘b‘.
Here is another exmaple code:
import re text = 'a456abc123' result = re.match('a4', text) print(type(result)) print(result) if result: print(result.group(0))
Run this code, the result is:
<class '_sre.SRE_Match'> <_sre.SRE_Match object; span=(0, 2), match='a4'> a4
It means text is started with ‘a4‘
Moreover, we also can use re.match() to check text starting with pattern or not.
import re text = 'a456abc123' result = re.match('[0-9]{1,3}', text) print(type(result)) print(result) if result: print(result.group(0))
Here result is also None, which means text is not started with numbers.