Python中的拆分和转义正斜杠
我有一个文件,其中包含形式为Python中的拆分和转义正斜杠,python,regex,replace,escaping,Python,Regex,Replace,Escaping,我有一个文件,其中包含形式为/pattern/replace/的perl风格正则表达式,我正试图将其作为已编译模式及其相关替换字符串的列表读入Python。下面是我到目前为止所做的 def get_regex(filename): regex = [] fi = open(filename,'r') text = [l for l in fi.readlines() if not l.startswith("#")] fi.close() for line
/pattern/replace/
的perl风格正则表达式,我正试图将其作为已编译模式及其相关替换字符串的列表读入Python。下面是我到目前为止所做的
def get_regex(filename):
regex = []
fi = open(filename,'r')
text = [l for l in fi.readlines() if not l.startswith("#")]
fi.close()
for line in text:
ptn, repl = line[1:].split('/')[:-1]
regex.append((re.compile(ptn), repl))
return regex
在我找到带有转义前斜杠的行之前,这一切都非常有效,如下所示:
/$/ <\\/a>/
/$//
当我尝试拆分这个字符串时,Python返回一个包含三个元素的列表,
['$',']
,而不是(希望的)['$',']
。有没有办法让replace
解释转义 不是真的,不是。你最好使用re.split()
来代替,使用一个使用lookback的正则表达式来确保不转义正斜杠,例如
UNESCAPED_SLASH_RE = re.compile(r'(?<!\\)/')
ptn, repl = UNESCAPED_SLASH_RE.split(line[1:])[:-1]
UNESCAPED\u SLASH\u RE=RE.compile(r'(?不是真的,不是。你最好的选择可能是使用RE.split()
,使用一个正则表达式,该正则表达式使用一个回溯来确保正斜杠不被转义,例如
UNESCAPED_SLASH_RE = re.compile(r'(?<!\\)/')
ptn, repl = UNESCAPED_SLASH_RE.split(line[1:])[:-1]
UNESCAPED\u SLASH\u RE=RE.compile(r'(?)?