Skip to main content
 首页 » 编程设计

Python3 正则表达式 : Remove all characters except/and | from string

2025年05月04日29bluestorm

我正在用 Python3 编写一个程序,我在一个变量中有一个字符串。此字符串包含大量 | 和 / 字符,以及可能的字母数字字符和空格。

我需要一个正则表达式来删除除| 和/ 之外的所有字符,并用空字符替换它们。

所以基本上,/|||/blah/|||||/foo/|/bar/|||/ 会变成 /|||//||| ||//|//|||/.

谁能帮我做这个?提前致谢

请您参考如下方法:

上面的也可以简写为re.sub('[^/|]'),即不需要对这两个字符进行转义。