python 中的多模式替换和空格
multipattern substitution along with whitespace in python
输入:
"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)
您可以使用
replDictRe = re.compile( r'(?<!\S)(?:{})(?!\S)'.format('|'.join(map(re.escape, new_.keys()))) )
参见online Python demo and the regex demo。
(?<!\S)(?:\&\&|\|\|)(?!\S)
模式表示
(?<!\S)
- 匹配前面没有紧跟非空白字符(又名左侧空白边界)的位置
(?:\&\&|\|\|)
- &&
或 ||
字符子串
(?!\S)
- 一个位置后面没有紧跟一个非空白字符(又名右侧空白边界)。
输入:
"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)
您可以使用
replDictRe = re.compile( r'(?<!\S)(?:{})(?!\S)'.format('|'.join(map(re.escape, new_.keys()))) )
参见online Python demo and the regex demo。
(?<!\S)(?:\&\&|\|\|)(?!\S)
模式表示
(?<!\S)
- 匹配前面没有紧跟非空白字符(又名左侧空白边界)的位置(?:\&\&|\|\|)
-&&
或||
字符子串(?!\S)
- 一个位置后面没有紧跟一个非空白字符(又名右侧空白边界)。