如何解决如何在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
,
您可以将(
的搜索限制在字符串开头以外的所有位置,并将)
的搜索限制在字符串末尾以外的所有位置:
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'\1 (',test)
为了测试
re.sub(r'(\D)([)]){1}',r'\1) ',test2 or test3)
对于test2和test3
,替换第一个括号,然后替换第二个括号
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。