Regular expression to search digit inside a string in python

524 viewsPython

Regular expression to search digit inside a string in python

The \d  is a special sequence that matches any digit between 0 to 9. Give here the example of sample code, how to use the Python re module to write the regular expression.

Farjanul Nayem Changed status to publish December 13, 2022
0

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

  1. We imported the RE module into our program
  2. Next, We created a regex pattern \d to match any digit between 0 to 9.
  3. After that, we used the re.findall() method to match our pattern.
  4. In the end, we got two digits 2 and 5.
Farjanul Nayem Answered question December 13, 2022
0