我有一个字符串,里面有一些相对路径,例如:
<AdditionalIncludeDirectories>..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
我想只为每条路径添加..\..\
。
我可以用replace
方法做到这一点,但问题是“up up”的数量不固定(取决于我想要替换的字符串)。
如果我尝试用..\
替换..\..\..\
,我的脚本会替换他找到的每个出现的内容。所以我在最终结果..\..\..\..\..\..\..\..\..\..\..\..\
上有以下内容。
所以我怎么只能在Python 3中为这个字符串中的每个路径添加2个“up step”。
期望的结果是:
<AdditionalIncludeDirectories>..\..\..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
答案 0 :(得分:1)
有更好的方法,但这应该有效。
a = 'AdditionalIncludeDirectories>..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>'
b = re.search('>(.*)<', a)## Get paths str position
paths_str = a[b.start() + 1:b.end() - 1]## paths_str
paths = paths_str.split(';')
full_paths = ['..\..\{0}'.format(path) for path in paths]## adding up dirs
full = '{0}>{1}<;{2}'.format(a[:b.start()], ';'.join(full_paths),
a[b.end():])## Combining together.
答案 1 :(得分:0)
您可以使用re
模块的正则表达式替换:
>>> s = '..\..\..\..\..\..\external\gmock\...;..\..\..\..\..\..\external...'
>>> import re
>>> print(re.sub(r'(\.\.\\)+', r"..\\..\\", s))
..\..\external\gmock\...;..\..\external...