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