Reputation: 95
This code is designed to remove everything but leave numbers
a = "1.1.1.1"
b = re.sub('[^0-9]', '', a)
but i want to preserve dots as well.
Upvotes: 7
Views: 8036
Reputation: 369064
Not using regular expression:
>>> ''.join(c for c in a if c.isdigit() or c == '.')
'1.1.1.1'
>>> a = 'hello.1.number'
>>> ''.join(c for c in a if c.isdigit() or c == '.')
'.1.'
Upvotes: 2
Reputation: 27423
>>> a='1.1.1.1'
>>> b = re.sub('[^0-9\.]', '', a)
>>> b
'1.1.1.1'
>>> a='comp.languages.python'
>>> b = re.sub('[^0-9.]', '', a)
>>> b
'..'
The []
means match only these characters.
The [^]
means match all characters EXCEPT these characters.
0-9
is 0123456789
.
is . but be careful with . because outside []
it is often used to match any single character
Upvotes: 3
Reputation: 180
Try out
a = 1.1.1.1
b = re.sub('[^\d\.]', '', a)
instead. 0-9
can be replaced with \d
because that matches all numerical characters, and the \.
is necessary because the .
character is a wildcard.
Upvotes: 8