简体   繁体   English

Python 正则表达式 - 替换所有出现的未以特定字符开头的关键字

[英]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.我试过^(?!#.*$)keywordkeyword前面至少有一个其他单词时它不起作用。

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.

相关问题 使用 Python 正则表达式替换特定上下文中的所有出现 - Substitute all occurrences within a specific context using Python regex Python,替换所有出现的事件 - Python, substitute all occurrences Python 正则表达式匹配关键字的所有变体,除非前面有大写单词 - Python Regex to match a all variations of a keyword except if preceded by a capitalized word Python正则表达式:替换所有出现的特定字符串,而不是在特定字符之后 - Python regex: substitute all occurrence of a certain string NOT after a specific character Python 正则表达式,如何用单个模式替换多次出现? - Python Regex, how to substitute multiple occurrences with a single pattern? Python 用于查找前面没有一组字符的数字的正则表达式解决方案 - Python Regex solution for finding numbers not preceded by a set of characters Python替换使用正则表达式找到的所有匹配项 - Python replace all occurrences found using regex 正则表达式,用于捕获所有出现的由字符序列分隔的文本 - Regex for capturing all occurrences of text delimited by a sequence of characters 使用 python 正则表达式查找所有出现的多个正则表达式条件 - Find all occurrences of multiple regex conditions using python regex 替换两个特定字符之间所有出现的字符 - Replace All occurrences of character between two specific characters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM