【问题标题】:splitting and escaped forward slashes in Python在 Python 中拆分和转义正斜杠
【发布时间】:2011-10-10 20:10:19
【问题描述】:

我有一个包含/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 返回一个包含三个元素的列表,['$', ' &lt;\\', 's&gt;'],而不是(希望的)['$', ' &lt;\\/s&gt;']。有没有办法让replace 解释转义?

【问题讨论】:

    标签: python regex replace escaping


    【解决方案1】:

    不是真的,不。您最好的选择可能是使用 re.split() 代替,使用正则表达式使用后向来确保正斜杠不会被转义,例如

    UNESCAPED_SLASH_RE = re.compile(r'(?<!\\)/')
    ptn, repl = UNESCAPED_SLASH_RE.split(line[1:])[:-1]
    

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      相关资源
      最近更新 更多