python - 我如何使用正则表达式在两个字符内获取一个字符串并删除该字符串内的某些字符
问题描述
我有一个要使用正则表达式过滤的长字符串
<@961483653468439706> Text to remove, this text is useless, that's why i want it gone!
i want this: `keep the letters and spaces`
我想保留 ` 字符之间的文本
唯一的问题是在我想要的字符串部分的每个字符之间都有一个不可见的字符。您可以在 regex101 中看到不可见字符:https ://regex101.com/r/rAYrMT/1
`([\'^\w]*)`
简而言之:将所有内容保留在 ` 之间,除了可以在此处找到的不可见字符信息:https ://apps.timwhitlock.info/unicode/inspect?s=%EF%BB%BF
解决方案
您可以过滤掉不可打印的字符:
import re
from string import printable
# your invisibles are in the string...
s='''<@961483653468439706> Text to remove, this text is useless, that's why i want it gone!
Type `keep the letters and spaces` and `this too`'''
for m in re.findall(r'`([^`]*)`', s):
print(repr(m))
print(''.join([c for c in m if c in printable]))
print()
印刷:
'k\ufeffe\ufeffe\ufeffp\ufeff \ufefft\ufeffh\ufeffe\ufeff \ufeffl\ufeffe\ufefft\ufefft\ufeffe\ufeffr\ufeffs a\ufeffn\ufeffd s\ufeffp\ufeffa\ufeffc\ufeffe\ufeffs'
keep the letters and spaces
'this too'
this too
推荐阅读
- matlab - 用 Matlab 绘制 3D 条形图
- git - 批处理响应:拨号 tcp:查找 gitlab.com:没有这样的主机
- javascript - 如何设置恒定的导入根路径?
- scheme - 有没有办法在重新定义特殊形式后取回它们?
- mysql - 如何将两个表与一列的位置连接起来
- java - 如何为类外的自定义对话框设置 onDismiss/CancelListener?
- spring - 流式传输时 S3 连接池超时
- java - 代理在 webDriver 中的 chromeOptions 中无法使用 Java 中的 selenium
- android - 如何修复三星设备中的地理围栏触发器,特别是最新的 s9 和 s10
- c# - SMBLibrary:“试图以访问权限禁止的方式访问套接字”