
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write Python Regular Expression to Get Numbers Except Decimal
Python's, regular expressions (regex) allow us to search, extract, and manipulate patterns in strings. Sometimes, If we want to extract only numbers from a string, except decimals, then we can use re.findall() method with a specific regex pattern.
The regex pattern was designed to specifically match the integer pattern. Let us first understand the regular expression used:
\b\d+\b
This pattern matches numbers like 10, 245, 89 but not 12.34 or 0.56 (decimals).
- \b : Word boundary to ensure we match standalone numbers.
- \d+ : One or more digits (0-9).
- \b : Ending word boundary.
Basic Extraction of Whole Numbers
This approach illustrates how to use a simple regex pattern \b\d+\b to get numbers except for decimals. The re.finall() function iterates over text to find characters that match the given pattern. It will return a list of every pattern match that occurs in a given string.
Example
In the following example, the re.findall() function searched the string using the regular expression pattern. This pattern extracts integers('30', '40') while excluding the decimal ' 25.5'.
import re text = "The temperatures are 30, 25.5, and 40 today." pattern = r'\b\d+\b' matches = re.findall(pattern, text) print(matches)
Following is the output of the above code -
['30', '25', '5', '40']
Extracting Numbers from a Mixed String
Here, we extract whole numbers from a string that includes both letters and mixed numerical formats. The same regex pattern, \b\d+\b, is used to filter out only the integers present.
Example
The following example retrieves '5' and '15' from the text, leaving out the decimal '10.5'.
import re text = "There are 5 apples, 10.5 oranges, and 15 bananas!" pattern = r'\b\d+\b' matches = re.findall(pattern, text) print(matches)
Following is the output of the above code 0
['5', '10', '5', '15']
Handling Negative Numbers
This method enhances the regex pattern to also demonstrate how to capture negative whole numbers by using \b-?\d+\b, where integers may have a negative sign.
Example
In the following example, the regex pattern identifies negative integers '-10' and '-5', along with '0' and '20'. The re.findall() function searched the text for all occurrences that match the regular expression pattern r'\b-?\d+\b', then returned a list containing all the matching strings.
import re text = "The temperatures are -10, -5, 0, and 20 degrees." pattern = r'\b-?\d+\b' matches = re.findall(pattern, text) print(matches)
Following is the output of the above code -
['-10', '-5', '0', '20']