Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python only find string with specific length numbers

Tags:

python

numbers

I am trying to create a script that search for strings of numbers with only specific length numbers from an output.txt.

Example output.txt:

12345678
77777
12123887

When I use:

import re 
f = open('output.txt', 'r')
strings = re.findall(r'(\d{5,5})', f.read())
print strings

I would like to get only output: 77777 instead of:

12345
77777
12123
like image 652
Jesse kraal Avatar asked Apr 21 '16 11:04

Jesse kraal


2 Answers

Use ^(\d{5})$ and re.MULTILINE

>>> import re
>>> data = '''12345678
77777
12123887'''
>>> p = re.compile(r'^(\d{5})$', re.MULTILINE)
>>> re.findall(p, data)
['77777']
>>>
like image 190
Praveen Avatar answered Nov 15 '22 04:11

Praveen


A non-regex solution. This can be done by just getting the length of each name and getting the one of interest by also validating isdigit:

with open('output.txt') as f:
    file_names = [name.strip() for name in f.readlines() if name.strip().isdigit() and len(name.strip()) == 5]

print(file_names)
like image 22
idjaw Avatar answered Nov 15 '22 02:11

idjaw