SYZYGY-DEV 333
SYZYGY-DEV 333

Reputation: 155

Python3 Regex: Remove all characters except / and | from string

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

Answers (3)

Kreg
Kreg

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

Coding Pig
Coding Pig

Reputation: 66

The above one can also be shortened as re.sub('[^/|]'), ie without needing to escape the two chars.

Upvotes: 3

Pirheas
Pirheas

Reputation: 332

import re
a = '/|||/ blah /|||||/ foo /|/ bar /|||/'
print(re.sub('[^/|\|]', '', a))

>>> /|||//|||||//|//|||/

Upvotes: 2

Related Questions