2016-11-08 92 views
0

我有XML,如文件與像標籤:替換反斜槓所有斜槓指定標記中的文件路徑

<id>SomeID</id> 
<datasource>C:/projects/my_project/my_file.jpg</datasource> 
<title>My title can include/and other characters</title> 
<abstract></abstract> 

我想改變這一切斜線反斜槓,但僅在標籤數據源(打開和關閉內標籤)。

什麼是一般的正則表達式語法來做到這一點? 更新:我終於得到了與蟒蛇第一工作液:

regex_01 = re.compile(".*<datasource>") 
regex_02 = re.compile("</datasource>.*") 
file_content = ""   
for line in source_file.readlines(): 
    if "<datasource>" in line: 
     start = regex_01.search(line).group() 
     end = regex_02.search(line).group() 
     part_to_replace = line.replace(start,"").replace(end,"") 
     replaced = part_to_replace.replace("/","\\") 
     file_content = file_content + start + replaced.strip() + end + "\n" 
    else: 
     file_content = file_content + line  

你可以建議一些更優雅?

+0

你可以使用'(* SKIP)(* FAIL)' - 它是什麼語言? (僅適用於Perl,PCRE和Python) – antoni

+0

@antoni我開始在記事本++中進行測試,但我認爲它不可能在那裏做,所以我熱衷於** python **解決方案** – Miro

回答

1

您可以用跳躍嘗試這種/失敗語法:

(?:<datasource>[^/]*?|.*(?=<datasource>)|(?=</datasource>).*)(*SKIP)(*FAIL)|/ 

看到它在這裏工作:https://regex101.com/r/86gc4d/1

但是這個是PCRE。在python中,(*FAIL)也可以是(?!),但對於(*SKIP)我不確定。

如果我沒有錯,應該在最新的python正則表達式引擎中添加:https://pypi.python.org/pypi/regex

你可以找到(*SKIP)(*FAIL)語法這裏的文檔:http://www.rexegg.com/backtracking-control-verbs.html#skipfail,它也說,它工作在Python該段的例子:

# Python 
# if you don't have the regex package, pip install regex 

import regex as mrab 

# print(regex.__version__) should output 2.4.76 or higher 
print(mrab.findall(r'{[^}]*}(*SKIP)(*FAIL)|\b\w+\b', 
        'good words {and bad} {ones}')) 
# ['good', 'words'] 

希望它能幫助!

+0

謝謝,最後,我創建了繁瑣但有效的代碼。不知道我有正則表達式,稍後會測試它,如果它工作,接受這個答案:) – Miro