Extract a number from a complicated string

Sion Arrowsmith siona at chiark.greenend.org.uk
Fri Dec 21 09:39:04 EST 2007


Gerardo Herzig  <gherzig at fmed.uba.ar> wrote:
>>My problem is that I need to extract from this string the number. For
>>instance in xyz.vs.1-81_1 I have to extract the number 81, and in
>>xyz.vs.1-1234_1 I need to get the number 1234.
>>
>>What is the easiest way of doing this ?
>If the strings looks *allways* that way, so its not to complicated:
> >>> number_regex = re.compile('-(\d+)_')
> [ ... ]

If the strings always look *exactly* like that, a regex is a massive
overkill:

>>> examples = 'xyz.vs.1-81_1', 'xyz.vs.1-1234_1', 'xyz.vs.1-56431_1'
>>> [ int(x[9:-2]) for x in examples ]
[81, 1234, 56431]

If the "xyz.vs.1" and trailing "1" are a bit more variable, then a
regex is still massive overkill:

>>> [ int(x[x.index('-')+1:x.rindex('_')]) for x in examples ]
[81, 1234, 56431]

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
        -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list