Parsing numbers in a given range with pyparsing
<p>How to extract numbers in a given range using pyparsing?
I tried:</p>

<pre><code># Number lower than 12:
number = Word(nums).addCondition(lambda tokens: int(tokens[0]) &lt; 12)

test_data = "10 23 11 14 115"
print number.searchString(test_data)
</code></pre>

<p>but it returns:</p>

<pre><code>[['10'], ['3'], ['11'], ['4'], ['5']]
</code></pre>

<p>What I want is:</p>

<pre><code>[['10'], ['11']]
</code></pre>

<p>More specified example:
I want to extract all numbers that looks like part of a date and ignore others.
So, from this input:</p>

<pre><code>"""
This is a date: 12 03 2008
This too: 03 12 2008
And this not, values are too large: 123 333 11
"""
</code></pre>

<p>I want to get:</p>

<pre><code>[[12, 3, 2008], [3, 12, 2008]]
</code></pre>

<p>The main issue here is that searchString (and the underlying scanString) go through the input string character by character looking for matches. So in your input (with position header for reference):</p>

<pre><code>          1
012345678901234 &lt;- position
10 23 11 14 115
</code></pre>

<p>searchString goes through the following steps:</p>

<ul>
<li>finds number "10" at position 0, this matches the "less than 12" condition, and so this is a match</li>
<li>advance to position 2</li>
<li>skipping whitespace, advance to position 3</li>
<li>finds number "23" at position 3, but this fails the condition</li>
<li>advance one place to position 3</li>
<li>finds number "3", this matches the condition, so is accepted as a match</li>
<li>finds number "11", this is a match, advance to position 8</li>
<li>skips whitespace, advance to position 9</li>
<li>finds number "14", this fails the condition</li>
<li>advance one place to position 10</li>
<li>finds number "4", this passes the condition, so accepted as a match </li>
<li>advances and finds number "115", and fails</li>
<li>advances one place and finds the number "15", and fails</li>
<li>advances one place and finds the number "5", and accepts as a match</li>
</ul>

<p>giving the results as you posted, <code>[['10'], ['3'], ['11'], ['4'], ['5']]</code>.</p>

<p>A quick solution is to change your definition of <code>number</code> to add <code>asKeyword=True</code>:</p>

<pre><code>number = Word(nums, asKeyword=True)
</code></pre>

<p>As keyword forces the expression to match only if at the beginning of a space-separated word. In your case, this will prevent accidental parsing of the '3' in '23', and the '4' in '14', etc.  This will give your desired result of <code>[['10'], ['11']]</code>.</p>

python pyparsing