Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 仅当字符串存在于两个子字符串之间时,才替换该字符串_Python_Regex - Fatal编程技术网

Python 仅当字符串存在于两个子字符串之间时,才替换该字符串

Python 仅当字符串存在于两个子字符串之间时,才替换该字符串,python,regex,Python,Regex,对于我的项目,我需要替换两个子字符串中的任何字符。我的意思是: string = "This is outside of the object. %This is inside the object.% Outside again!" 用-替换%中的任何“”后,字符串应该是这样的: This is outside of the object. %This-is-inside-the-object.% Outside again! 我可以使用什么功能来执行此操作 strin

对于我的项目,我需要替换两个子字符串中的任何字符。我的意思是:

string = "This is outside of the object. %This is inside the object.% Outside again!"
-
替换
%
中的任何
”后,字符串应该是这样的:

This is outside of the object. %This-is-inside-the-object.% Outside again!
我可以使用什么功能来执行此操作

string = "This is outside of the object. %This is inside the object.% Outside again!"
import re
Variable2 = re.sub("%[^%]*%", lambda x:x.group(0).replace(' ','-'), string)
输出

'This is outside of the object. %This-is-inside-the-object.% Outside again!'

该字符串的行为应该如何<代码>外部%这是内部%what now?%Outside它的行为应该类似于打开/关闭字符串的方式。假设您有一个字符串,
这在外面,%now in%这是一个未关闭的区域%now in这实际上在外面
。如果有未关闭的区域,我宁愿忽略它,这样替换的字符串就会变成
这是外部,%now inside%这是未关闭的区域%,这实际上在上面的注释之外。如果它存在于两个子字符串之间,我只需要将其替换。@liked21每个开头
%
是否都有一个结尾
%
?换句话说,字符串是否保证总是有偶数个
%
字符?因为如果不是,我认为在python中使用纯正则表达式是不可能的。但我可能错了。一个简单的非正则表达式解决方案是在
%
上拆分字符串,然后在数组的每一个元素(最后一个元素除外)中用连字符替换空格字符来迭代数组。然后,您可以将数组重新加入到一个字符串中。我不确定
[^]]
的目的是什么。您是否打算使用
[^%]
?是的,您是对的,我对python也很陌生…因此我没有完全考虑清楚。如果我错了,很抱歉。有什么方法可以对单独的子字符串起作用吗?就像
。不管怎样,我找到了。正则表达式模式是
\([^\(\)]*\)