首页 > 解决方案 > 正则表达式查询:删除转义字符但保留字符串中的标点符号

问题描述

我有一个类似于 - 的字符串"\n\n\some text\t goes here. some\t\t other text goes here\b\n\n\n"

我想要的是 -"some text goes here. some other text goes here."

这是我正在做的事情:re.sub('[^A-Za-z0-9]+', ' ', s)

问题是这也会删除所有标点符号。我如何保留这些?

标签: regexpython-3.xstring

解决方案


这是一个解决方案,可以找到字符串中的所有转义字符,然后将其删除。

r = repr(s)  # Convert escape sequences to literal backslashes
r = r[1:-1]  # Remove the quote characters introduced by `repr`
escapes = set(re.findall(r'\\\w\d*', r))  # Get escape chars
answer = re.sub('|'.join(map(re.escape, escapes)), '', r)  # Remove them
# \ome text goes here. some other text goes here

推荐阅读