HS Banner
Back
Find all the Numbers Using Regular Expression

Author: Admin 02/16/2026
Language: Python
Tags: python open file sum regular expression


Description:

This code opens a text file and uses regular expression to find all the number and puts them in a list to get the sum.

Article:

# Open a text file
fname = input("Enter the file name: ")
if len(fname) < 1: fname = 'MyTextFile.txt' # Check for file name
try:
    fhand = open(fname, 'r')
    f = fhand.read()
except:
    print('File cannot be opened:', fname)
    quit()

# Find numbers in a text file, create a list, and sum.
numbers_list = re.findall(r'[0-9]+', f)
num_list = list()
for num in numbers_list:
    num_list.append(int(num))

print(sum(num_list))

Python Regular Expression Guide

# ^        Matches the beginning of a line
# $        Matches the end of the line
# .        Matches any character
# \s       Matches whitespace
# \S       Matches any non-whitespace character
# *        Repeats a character zero or more times
# *?       Repeats a character zero or more times
#          (non-greedy)
# +        Repeats a character one or more times
# +?       Repeats a character one or more times
#          (non-greedy)
# [aeiou]  Matches a single character in the listed set
# [^XYZ]   Matches a single character not in the listed set
# [a-z0-9] The set of characters can include a range
# (        Indicates where string extraction is to start
# )        Indicates where string extraction is to end



Back
Comments
Add Comment
There are no comments yet.