Reputation: 155
I am writing a program in Python3, and I have a string in a variable. This string contains lots of |
and /
characters, as well as possible alphanumeric characters and whitespace.
I need a regular expression to get rid of all characters except |
and /
, and replace them with nothing.
So basically, /|||/ blah /|||||/ foo /|/ bar /|||/
would become /|||//|||||//|//|||/
.
Can anyone help me do this? Thanks in advance
Upvotes: 2
Views: 2986
Reputation: 71
Use regex for this. http://regexr.com/ is a great tool to write your own, but I did it for you below.
import re #import regex module
str = '/|||/ blah /|||||/ foo /|/ bar /|||/'
str = re.sub(r"[^|/]", "", str) #replaces everything that is not | or /
print(str)
Upvotes: 1
Reputation: 66
The above one can also be shortened as re.sub('[^/|]')
, ie without needing to escape the two chars.
Upvotes: 3
Reputation: 332
import re
a = '/|||/ blah /|||||/ foo /|/ bar /|||/'
print(re.sub('[^/|\|]', '', a))
>>> /|||//|||||//|//|||/
Upvotes: 2