2016-11-08 119 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