I’m trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don’t want that. I’ve been trying many regular expressions with no success.
Thanks!
JavaScript
x
4
1
s = "This must not b3 delet3d, but the number at the end yes 134411"
2
s = re.sub("d+", "", s)
3
print s
4
Result:
This must not b deletd, but the number at the end yes
Advertisement
Answer
Add a space before the d+.
JavaScript
1
5
1
>>> s = "This must not b3 delet3d, but the number at the end yes 134411"
2
>>> s = re.sub(" d+", " ", s)
3
>>> s
4
'This must not b3 delet3d, but the number at the end yes '
5
Edit: After looking at the comments, I decided to form a more complete answer. I think this accounts for all the cases.
JavaScript
1
2
1
s = re.sub("^d+s|sd+s|sd+$", " ", s)
2