Reading after a symbol..
Jonas H.
jonas at lophus.org
Tue Oct 12 23:20:55 CEST 2010
On 10/12/2010 10:48 PM, Pratik Khemka wrote:
> Likewise I want to read the number after the '#' and store it in num. The problem is that the number can be a 1/2/3/4 digit number. So is there a way in which I can define num so that it contains the number after '#' irrespective of how many digits the number is. Because the problem is that the above code will not work for scenarios when the number is not 2 digits..
Easy with regular expressions:
>>> re.search('(\d{2,4}})', 'foo123bar').group(1)
'123'
That regular expression basically means "match any sequence of 2 to 4
digits (0-9)". Note that this would also match against a sequence that
is not surrounded by non-digits (hence, a sequence that is longer than 4
digits). You could work around that with something like this:
[^\d](\d{2,4})[^\d]
That's the expression used above but encapsulated with '[^\d]', which
stands for "anything but a digit", so the complete expression now
matches against "all sequence of 2 to 4 digits that is surrounded by
non-digits". Note that this expression wouldn't match against a string
that has no surrounding characters. So for example '1234' or '1234a' or
'a1234' won't be matched, but 'a1234b' will be.
Hope this helps :-)
Jonas
More information about the Python-list
mailing list