python - 如何在 Python 中使用 Re 库在括号和字符串之间添加空格?
问题描述
我有 3 个不同的字符串,如果字符串和括号之间没有空格(如果有转义,请勿触摸),我必须在括号前后添加空格。对我来说,它看起来非常复杂的 Re 库,我无法弄清楚。特别是当我使用括号时。
test = "example(test)"
test2 = "example(test)example"
test3 = "(test)example"
我必须在一个重新功能中完成所有这些。
result = re.sub(r"Some code for all of them","Space here",test or test2 or test3)
print(result)
输出
test = "example (test)"
test2 = "example (test) example"
test3 = "(test) example"
我知道它看起来很多,但句尾不应该有空格。
解决方案
这是一种方法
import re
test = "example(test)"
test2 = "example(test)example"
test3 = "(test)example"
test4 = "example (test) example"
for i in [test, test2, test3, test4]:
print(re.sub(r"[^\S]?(\(.*?\))[^\S]?", r" \1 ", i).strip())
输出:
example (test)
example (test) example
(test) example
example (test) example
推荐阅读
- python - TypeError:字符串索引必须是整数django
- cmake - 具有多个源文件的 ESP-IDF 项目
- django - 为什么我的远程服务器无法连接到另一个 Django 服务器上的 postgres 实例?
- qt - Yubikey 在 Ubuntu 20.04 上的 Qt 应用程序中将密码的小写字母转换为大写字母
- ios - 在 xamarin ios 数字键盘中添加减号按钮
- rust - 何时在 Rust 中使用 ref?
- google-vault-api - 关于使用 python 程序的 Google Vault API 的错误
- angular - 如何使用向上和向下键在垫子表中导航?
- c# - OData 正在删除我在 Swagger 中的现有参数
- azure - 带有事件中心触发器的 Azure 函数接收到奇怪数量的事件