How to match any non-digit character in Python using Regular Expression?


A regular expression is a group of characters that allows you to use a search pattern to find a string or a set of strings. RegEx is another name for regular expressions. The re module in Python is used to work with regular expressions.

In this article we look how to extract non digit characters in python by using regular expression. We use \D+ regular expression in python to get non digit characters from a string.

Where,

  • \D returns a match that does not contain digits.
  • + implies zero or more occurrences of characters.

Using findall() function

In the following example, let us assume ‘2018Tutorials point’ as a string where we need to eliminate 2018 which is a digit and must extract Tutorials point.

Example

In the following example code, we use findAll() function to match any non-digit character in python using regular expression. We begin by importing the regular expression module.

import re

Then, we have used findall() function which is imported from the re module.

import re string = "2018Tutorials point" pattern= [r'\D+'] for i in pattern: match= re.findall(i, string) print(match)

The re.findall() function returns a list containing all matches, that is list of strings with non-digits.

Output

On executing the above program, the following output is obtained.

['Tutorials point']

Example

Let us see another example where a string has multiple digits. Here, we assume ‘5 childrens 3 boys 2 girls’ as an input phrase. The output should return all the strings with non-digits.

import re string = "5 childrens 3 boys 2 girls" pattern= [r'\D+'] for i in pattern: match= re.findall(i, string) print(match)

Output

On executing the above program, the following output is obtained.

[' childrens ', ' boys ', ' girls']

Using search() function

In the following code, we match ‘5 childrens 3 boys 2 girls’ string where all the strings with non-digits are extracted ‘childrens boys girls’.

Example

In the following example code, we use search() function to match any non-digit character in python using regular expression. We begin by importing regular expression module.

import re

Then, we have used search() function which is imported from the re module to get the required string. This re.search() function searches the string/paragraph for a match and returns a match object if there is any match. The group() method is used to return the part of the string that is matched.

import re phrase = 'RANDOM 5childerns 3 boys 2 girls//' pattern = r'(?<=RANDOM).*?(?=//)' match = re.search(pattern, phrase) text = match.group(0) nonDigit = re.sub(r'\d', '', text) print(nonDigit)

Output

On executing the above program, the following output is obtained.

childerns  boys  girls

Updated on: 08-Nov-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements