2014-07-24 145 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)