簡體   English   中英

帶正則表達式的Python文本處理

[英]Python text processing with regular expression

我使用的是Python 2.7.5。 我在目錄/子目錄中有一些文件。 下面給出了file1示例

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 我希望得到的最終結果如下:

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查找並替換字符串。 但是我從來沒有得到我想要的輸出。

這種單線完成了整個轉換:

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

觀看此代碼的現場演示

您可以嘗試以下方法:

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

最后1是僅指示第一匹配,使得僅所述第一路徑是取代的。

順便說一句,我認為您想保留空格/制表符或逗號對嗎? 使replace_text像這樣:

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

好。 得到了波希米亞和傑里的答案。 與組合代碼一起使用。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM