We will use the (
\d ) metacharacter, we will discuss regex metacharacters in detail in the later section of this article.
Let’s take a simple example of a regular expression to check if a string contains a number.
# import RE module import re target_str = "My roll number is 25" res = re.findall(r"\d", target_str) # extract mathing value print(res) # Output [2, 5]
Understand this example
- We imported the RE module into our program
- Next, We created a regex pattern
\dto match any digit between 0 to 9.
- After that, we used the
re.findall()method to match our pattern.
- In the end, we got two digits 2 and 5.