Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于修改路径的Python正则表达式_Python_Regex - Fatal编程技术网

用于修改路径的Python正则表达式

用于修改路径的Python正则表达式,python,regex,Python,Regex,我需要用字符串替换XML文件中的一些路径 所有要更改的路径都以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)

我需要用字符串替换XML文件中的一些路径

所有要更改的路径都以
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["])'

regex=”(?原始文本是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)
正则表达式:

替换字符串:

\1"\3\4

示例:

>>> 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"/>'

下面的字符串是您预期的结果吗?@AvinashRaj,是的,这是预期的结果results@Dcow你是说这个吗?@AvinashRaj,我需要保存旧文件名,只修改路径。别忘了在普通字符串表达式中引用反斜杠。
\s
应该是
\\s
。这次你侥幸逃脱了,因为
\s
没有反斜杠特别的意思,但它通常会咬你。还有,当你不需要包含控制字符时(就像你在本例中所做的那样),它们会更好。
>>> 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"/>'