[英]Python regex replace capture
I'm trying to add one space before and after +-
, using re.sub
(only) what expression to use? 我正在尝试在+-
之前和之后添加一个空格,使用re.sub
(仅)使用什么表达式?
import re
text = """a+b
a+b-c
a + b - c
a+b-c+d-e
a + b - c + d - e"""
text = re.sub('(\s?[+-]\s?)', r' \1 ', text)
print(text)
expected result: 预期结果:
a + b
a + b - c
a + b - c
a + b - c + d - e
a + b - c + d - e
<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script> <div data-datacamp-exercise data-lang="python"> <code data-type="sample-code"> import re text = """a+b a+bc a + b - c a+b-c+de a + b - c + d - e """ text = re.sub('(\\s?[+-]\\s?)', r' \\1 ', text) print(text) </code> </div>
Try capturing only the [+-]
, and then replace with that group surrounded by spaces: 尝试仅捕获[+-]
,然后替换为由空格包围的组:
text = re.sub('\s?([+-])\s?', r' \1 ', text)
<script type="text/javascript" src="//cdn.datacamp.com/dcl-react.js.gz"></script> <div data-datacamp-exercise data-lang="python"> <code data-type="sample-code"> import re text = """a+b a+bc a + b - c a+b-c+de a + b - c + d - e """ text = re.sub('\\s?([+-])\\s?', r' \\1 ', text) print(text) </code> </div>
You also might consider repeating the \\s
s with *
instead of ?
您也可以考虑用*
而不是?
重复\\s
s ?
, so that, for example, 3 + 5
gets prettified to 3 + 5
: ,例如, 3 + 5
被美化为3 + 5
:
\s*([+-])\s*
You can use a lambda
function with re.sub
: 你可以使用带有re.sub
的lambda
函数:
import re
new_text = re.sub('(?<=\S)[\+\-](?=\S)', lambda x:f' {x.group()} ', text)
Output: 输出:
a + b
a + b - c
a + b - c
a + b - c + d - e
a + b - c + d - e
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.