Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.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_Replace_Escaping - Fatal编程技术网

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'(?)?