Find all items in a list that match a specific format
<p>I am trying to find everything in a list that has an format like "######-##"</p>

<p>I thought I had the right idea in my following code, but it isn't printing anything. Some values in my list have that format, and I would think it should print it. Could you tell me what's wrong?</p>

<pre><code>for line in list_nums:
    if (line[-1:].isdigit()):
        if (line[-2:-1].isdigit()):
            if (line[-6:-5].isdigit()):
                if ("-" in line[-3:-2]):
                    print(list_nums)
</code></pre>

<p>The values in my list consist of formats like 123456-56 and 123456-98-98, which is why what I did above. It is pulled from an excel sheet.</p>

<p><strong>This is my updated code.</strong></p>

<pre><code>import xlrd
from re import compile, match

file_location = "R:/emily/emilylistnum.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
regexp = compile(r'^\d{d}-\d{2}$')
list_nums = ""


for row in range(sheet.nrows):
    cell = sheet.cell_value(row,0)
    if regexp.match(cell):
        list_nums += cell + "\n"
        print(list_nums)
</code></pre>

<p><strong>my excel sheet consists of:</strong> 
581094-001
581095-001
581096-001
581097-01
5586987-007
SMX53-5567-53BP
552392-01-01
552392-02
552392-03-01
552392-10-01
552392-10-01
580062
580063
580065
580065
580066
543921-01
556664-55</p>

<p>(in each cell down in one column)</p>

<p>If you need to only match the pattern <code>######-##</code> (where <code>#</code> is a digit):</p>

<pre><code>&gt;&gt;&gt; from re import compile, match
&gt;&gt;&gt; regexp = compile(r'^\d{6}-\d{2}$')
&gt;&gt;&gt; print([line for line in list_nums if regexp.match(line)])
['132456-78']
</code></pre>

<hr>

<h1>Explanations</h1>

<p>You <code>compile</code> the pattern into a regexp object to be more efficient when matching. The regexp is <code>^\d{6}-\d{2}$</code> where:</p>

<pre><code>^  # start of the line
\d{6}-\d{2}  # 6 digits, one dot then 2 digits
$  # end of the line
</code></pre>

<p>In the regexp, <code>\d</code> means digit (an integer from 0 to 9) and <code>{6}</code> means 6 times. So <code>\d{3}</code> means 3 digits. You should read the Python documentation about <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regexp</a>s.</p>

<hr>

<h1>Full code</h1>

<p>An example based on your comment:</p>

<pre><code>file_location = 'file.xlsx'
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
regexp = compile(r'^\d{6}-\d{2}$')

list_nums = ''
for row in range(sheet.nrows):
    cell = sheet.cell_value(row, 0)
    if regexp.match(cell):
        list_nums += cell + "\n"
</code></pre>

python loops for-loop