如何在 Python 中使用 Re 库在括号和字符串之间添加 space?

How can I add space between parentheses and string with Re library in Python?

我有3个不同的字符串,如果字符串和括号之间没有space(如果有转义,不要碰),我必须在括号前后添加space . 对我来说,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"

我知道看起来很多但是句末应该没有space

您可以将 ( 的搜索限制在除字符串开头以外的所有位置,并将 ) 的搜索限制在除字符串结尾之外的所有位置:

result = re.sub(r"\)(?!$)",") ", re.sub(r"(?<!^)\("," (", some_test))

为了应对可能存在的空白:

result = re.sub(r"\)(?!\s)(?!$)",") ", re.sub(r"(?<!^)(?<!\s)\("," (", some_test))

你需要这些正则表达式

re.sub(r'(\D{1})([(])',r' (',test)

待测

re.sub(r'(\D)([)]){1}',r') ',test2 or test3)

对于测试 2 和测试 3

替换第一个括号,然后替换第二个

import re

test = "example(test)"
test2 = "example(test)example"
test3 = "(test)example"

for_test = re.sub(r"\(","( ",test)
for_test2 = re.sub(r"\(","( ",test2)
for_test3 = re.sub(r"\(","( ",test3)


output_test = re.sub(r"\)"," )",for_test)
output_test2 = re.sub(r"\)"," )",for_test2)
output_test3 = re.sub(r"\)"," )",for_test3)
print(output_test)
print(output_test2)
print(output_test3)

输出

example( test )
example( test )example
( 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"  ", i).strip())

输出:

example (test)
example (test) example
(test) example
example (test) example