2017-06-06 157 views
0

我是新來的正則表達式,並試圖解決以下問題。Python正則表達式將文本中的絕對路徑替換爲用引號添加的相對路徑

輸入字符串 - String that has a path as /Users/MyName/moreofPath/ with additional text

輸出String - String that has a path as "$relativePath/moreofPath/" with additional text

在句子的絕對路徑是由

1)被識別,其中/Users/MyName開始

2)其中最後/那在任何其他特殊字符或空格結束之前出現

這應該用引號中的相對路徑替換。 有人可以幫我找到正確的正則表達式。

+1

我建議你擦亮你的問題了一下,我沒有完全理解它。 – Deano

+0

@Deano請你現在檢查一下。 –

+0

您確定您確實需要正則表達式來更改字符串的前綴嗎? –

回答

1

因爲它是所有的Python,我會做這樣的事情:

import re 

thestring = "String that has a path as /Users/MyName/moreofPath/evenmore/ with additional text" 
regex = "(.*?)/Users/MyName/(.*/)" 
thestring = re.sub(regex, r'\1"$relativePath/\2"' , thestring) 
print (thestring) 

輸出:

String that has a path as "$relativePath/moreofPath/evenmore/" with additional text 

我在做什麼是抓住了比賽中從parans並代回在更換。需要注意的是,*使得貪婪,直至最後使用/

+0

要添加,我正在尋找其中保留其餘文本的大文本中的絕對路徑替換ie)「具有/ Users/MyName/moreofPath /帶附加文本的路徑的字符串」是實際的字符串我需要將輸出的相對路徑用引號括起來。你的更新後的代碼給出了「./reedy/moreofPath/與額外的文本」,但輸出,但我需要「字符串有一個路徑爲」$ relativePath/moreofPath /「與額外的文本」作爲輸出(帶有路徑引號) –

+0

哦我想想我明白你的意思,讓我寫出來 – sniperd

+0

非常感謝您的更新 –

0

正則表達式通過用戶名,只要它不是空間匹配任何路徑遵循

import re 
input_string = "String that has a path as /Users/MyName/moreofPath/ with additional text" 
output_string = re.sub(r'/Users/MyName([^\s]*)', r'"$relativePath\1"', input_string) 
# 'String that has a path as "$relativePath/moreofPath/" with additional text'