【问题标题】:multipattern substitution along with whitespace in python多模式替换以及python中的空格
【发布时间】:2020-03-19 00:04:58
【问题描述】:

输入:

"good && toast&&guest &fast& slow||wind ||old|| new || very good"

要求:将" && " 替换为"and"(类似地将" || " 替换为"or")所以我上面的输出应该如下:

"good and toast&&guest &fast& slow||wind ||old|| new or very good"

我想做什么:

import re

new_ = {
                                '&&':'and',
                                '||':'or'
}

inpStr = "good && toast&&guest &fast& slow||wind ||old|| new || very good"
replDictRe = re.compile( r'(\s%s\s)' % '\s|\s'.join(map(re.escape, new_.keys())))
oidDesStr = replDictRe.sub(lambda mo:new_.get(mo.group(),mo.group()), inpStr)
print(oidDesStr)

【问题讨论】:

    标签: regex python-3.x substitution


    【解决方案1】:

    你可以使用

    replDictRe = re.compile( r'(?<!\S)(?:{})(?!\S)'.format('|'.join(map(re.escape, new_.keys()))) )
    

    请参阅online Python demoregex demo

    (?&lt;!\S)(?:\&amp;\&amp;|\|\|)(?!\S) 模式表示

    • (?&lt;!\S) - 匹配一个没有紧跟非空白字符(又名左侧空白边界)的位置
    • (?:\&amp;\&amp;|\|\|) - &amp;&amp;|| 字符子字符串
    • (?!\S) - 一个没有紧跟非空白字符(又名右侧空白边界)的位置。

    【讨论】:

    • 任何建议为什么下面不起作用```replDictRe = re.compile(r'(\s)(?:{})(\s)'.format('|'.join (map(re.escape,new_.keys())))) ```
    • @sakeesh 您的匹配值包含空格,但您的字典键不包含。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2011-01-05
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多