2013-09-29 23 views
1

我使用python 2.7.5。 我在目錄/子目錄中有一些文件。在file1的示例如下用正則表達式處理Python文本

Title file name 
    path1 /path/to/file 
    options path2=/path/to/file1,/path/to/file2,/path/to/file3,/path/to/file4 some_vale1 some_vale2 some_value3=abcdefg some_value4=/path/to/value some_value5 

給予我想插入文本文件中的文本/root/directory。最後的結果我想有是followes: -

Title file name 
    path1 /root/directory/path/tofile 
    path2=/root/directory/path/to/file1,/root/directory/path/to/file2,/root/directory/path/to/file3,/root/directory/path/to/file4 
    options some_vale1 some_vale2 some_value3=abcdefg some_value4=/path/to/value some_value5 

名稱path, options and path2在所有文件一樣。目錄/子目錄中的文件需要使用與上述相同的結果進行修改。我試圖用re.sub找到並替換字符串。然而,我從來沒有得到我想要的輸出。

+0

你可以把你嘗試過的're.sub'嗎? – Jerry

+0

're.sub(r「([\ t =,])/」,replace_text,text)'其中'replace_text =/root /目錄'和文本是用'.read()'加載的文件的內容。截至目前,我只是想弄清楚替換/插入。將path2連接到下一行是另一回事。 –

回答

0

確定。從波西米亞和傑瑞那裏得到了答案。得到它與組合代碼的工作。

str = re.sub(r'(options) (\S+)', r'\2\n \1', re.sub(r'([ \t =,])/', replace_text, text)) 
0

你可以試試這個:

result = re.sub(r'([ \t =,])/', replace_text, text, 1) 

最後1是隻表示第一場比賽,所以只有第一條路徑將被替換。

順便說一句,我認爲你想節省的空間/選項卡或逗號對嗎?讓REPLACE_TEXT這樣的:

replace_text = r'\1/root/directory/' 
+0

完美的工作。不過,我不得不刪除我需要替換所有匹配的字符串的廣告。你能告訴我'\ 1'在'r'\ 1/root/directory /'中做了什麼'現在來看第二部分。我如何獲得下一行的path2行? –

+0

@sundar_ima對不起,我沒有得到你的評論的通知:('\ 1'匹配捕獲的組,所以你保留你捕獲的部分;否則,它最終會成爲'path1/root /目錄/ path/tofile'。另外,沒關係,我認爲'path2'是單獨的,並且需要單獨的're.sub'。'options'中的部分是否由空格分隔?並且總是存在4條路徑和5個值? – Jerry

+0

感謝您的澄清。是的,'option'總是由空格隔開,甚至是'path2 =/path/to/file1'也是由空格隔開。有些情況下path1,options和path2已經在不同的線條。 –

1

這一個班輪執行了全部的轉換:

str = re.sub(r'(options) (\S+)', r'\2\n \1', str.replace('/path/', '/root/directory/path/') 

查看此代碼的live demo