Reputation: 1790
I've a string, with some relative paths inside, like the following for example:
<AdditionalIncludeDirectories>..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
And I want to only add ..\..\
for each path.
I can do that with replace
method, but the problem here is that the number of "up step" is not fixed (dependending of the string I want to replace).
If I try to just replace ..\
with something like ..\..\..\
my script replace each occurence he found. So I have the following at final result ..\..\..\..\..\..\..\..\..\..\..\..\
.
So how I can only add 2 "up step" to each path in this string in Python 3.
The desired result is:
<AdditionalIncludeDirectories>..\..\..\..\..\..\..\..\external\gmock\gmock-1.7.0\include;..\..\..\..\..\..\..\..\external\gmock\gmock-1.7.0\gtest\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
Upvotes: 1
Views: 70
Reputation: 73470
You can use the regex substitution of the re
module:
>>> s = '..\..\..\..\..\..\external\gmock\...;..\..\..\..\..\..\external...'
>>> import re
>>> print(re.sub(r'(\.\.\\)+', r"..\\..\\", s))
..\..\external\gmock\...;..\..\external...
Upvotes: 0
Reputation: 387
There are better ways but this should work.
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.
Upvotes: 1