[英]Python regex - substitute all occurrences of keyword not preceded by specific characters
Problem问题
I'm trying to replace all occurrences of keyword
not preceded by #
or [[
with [[keyword]]
.我想,以取代所有出现的
keyword
不是由前面#
或[[
与[[keyword]]
。
For instance, the strings例如,字符串
keyword
#keyword
some keyword
[[keyword]] keyword
would be replaced with将被替换为
[[keyword]]
#keyword
some [[keyword]]
[[keyword]] [[keyword]]
Attempt试图
I've tried ^(?!#.*$)keyword
which does not work when keyword
has at least one other word in front of it.我试过
^(?!#.*$)keyword
当keyword
前面至少有一个其他单词时它不起作用。
Removing the ^
however causes all occurrences of keyword
to be replaced, including the ones directly after a pound sign and brackets.然而,删除
^
会导致所有出现的keyword
被替换,包括直接在井号和括号之后的那些。
Question问题
How can I replace all occurrences of keyword
except when following a #
or [[
?除了跟随
#
或[[
时,如何替换所有出现的keyword
?
You can use您可以使用
\b(?<!\[\[)(?<!#)keyword\b
See the regex demo .请参阅正则表达式演示。 Details :
详情:
\\b
- a word boundary \\b
- 单词边界(?<!\\[\\[)
- no [[
substring is allowed immediately on the left (?<!\\[\\[)
- 左边不允许立即出现[[
子串(?<!#)
- no #
char is allowed immediately on the left (?<!#)
- 左边不允许使用#
字符keyword
- a string keyword
- 一个字符串\\b
- word boundary. \\b
- 字边界。 See the Python demo :请参阅Python 演示:
import re
text = "keyword\n#keyword\nsome keyword\n[[keyword]] keyword"
print( re.sub(r'\b(?<!\[\[)(?<!#)keyword\b', r'[[\g<0>]]', text) )
## => [[keyword]]
## => #keyword
## => some [[keyword]]
## => [[keyword]] [[keyword]]
Note the [[\\g<0>]]
replacement contains a backreference to the whole match, \\g<0>
.请注意,
[[\\g<0>]]
替换包含对整个匹配项的反向引用\\g<0>
。 You may want to use \\1
if you add capturing parentheses around keyword
in the regex pattern.如果您在正则表达式模式中的
keyword
周围添加捕获括号,您可能需要使用\\1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.