2014-07-24 147 views
1

我需要用我的字符串替换XML文件中的一些路径。Python正则表达式修改路径

所有要更改的路径都以schemaLocation=location=开头,后跟带扩展名的路径和文件名。

一些例子:

FROM 

    'schemaLocation="http://docs.oasis-open.org/wsn/b-2.xsd"/>' (1) 
    or 
    'schemaLocation= 
      "http://docs.oasis-open.org/wsn/b-2.xsd"/>' (2) 
    or 
    'schemaLocation="b-2.xsd"/>' (3) 

TO 

    'schemaLocation="b-2.xsd"/>' (4) in this sample new path is clear 
    or 
    'schemaLocation="../xsd/b-2.xsd"/>' (5) where "../xsd/" is new path 

我写

regex = '(?<=schemaLocation=)([\s]*[\r\n]*[\s]*".*[/]?)(?=.+[.]xsd["])' 

但我不能修改它从(3)处理(5)。

+2

下面的字符串是你的预期结果吗? –

+1

显然他们是? – trainoasis

+0

@AvinashRaj,是的,这是预期的结果 – Dcow

回答

0

正则表达式:

(schemaLocation=)\s*\"(.*\/)?(.*\")(.*) 

替换字符串:

\1"\3\4 

DEMO

实施例:

>>> s = """schemaLocation= 
...    "http://docs.oasis-open.org/wsn/b-2.xsd"/>""" 
>>> re.sub(r'(schemaLocation=)\s*\"(.*\/)?(.*\")(.*)', r'\1"\3\4', s, re.M) 
'schemaLocation="b-2.xsd"/>' 
0

原始文本是XML的事实在这里似乎没有起作用。 您可以使用re.sub相当不错的功能,即通过 函数来计算替换字符串的功能。 例如:

import re 
text = "...." # your text 
r = re.compile('(schemaLocation=")([^"]+)"') 

def repl(matchobj): 
    if matchobj.group(2) == 'types.xsd': 
     s = '../xsd/b-2.xsd' 
    else: 
     s = '...' # other cases 
    return matchobj.group(1) + s 


out = r.sub(repl, text)