0

I have the following string:

s = Promo 77

I am trying to get the output "77".

The following is the regex I am using:

>>> re.sub(r'^[0-9]','',s)
'Promo 77'

What should the correct statement be here?

David542
  • 104,438
  • 178
  • 489
  • 842

3 Answers3

4
>>> s = 'Promo 77'
>>> "".join(i for i in s if i.isdigit())
'77'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • It's better to pass a list comprehension than a generator expression to `str.join`; see http://stackoverflow.com/q/9060653/3001761 – jonrsharpe Jul 15 '14 at 23:01
2

You simply need to move the ^. r'^[0-9]' matches the beginning of the string, followed by a digit (which does not appear in your string). You want r'[^0-9]', which matches any character that is not a digit, or r'\D', which matches exactly the same set of characters.

murgatroid99
  • 19,007
  • 10
  • 60
  • 95
1
s = "Promo 77"
print re.findall("\d+",s)
['77']
print s.split()[-1]
77
re.sub(r'\D', "", s)
77
re.sub(r"[^\d+]","",s)
77
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321