简体   繁体   English

Python 使用lookahead/lookbehind替换整个单词

[英]Python replace whole word using lookahead/lookbehind

Using look ahead and look behind in regex how can i replace the following words succefully using python without replacing other words that appear similar.在正则表达式中使用向前看和向后看如何使用 python 成功替换以下单词而不替换其他看起来相似的单词。

css = '''
     selection-background-color: primary;
     selection-background-color:primary;
     selection-color: text-primary;
     selection-background-color: primary-text;
'''

I was trying to use this (?<?\w)primary(?=\w) based on what I was researching online but I'm not super familiar with regex and the best way to write this.我试图根据我在网上研究的内容来使用这个(?<?\w)primary(?=\w)但我对正则表达式和编写这个的最佳方式并不十分熟悉。

I would expect my results from the code above to create this...我希望我从上面的代码中得到的结果可以创建这个......

css = css.replace('primary', 'rgb(255,255,255)')
css = css.replace('primary-text', 'red')
css = css.replace('text-primary', 'green')

returns:返回:

css = '''
     selection-background-color: rgb(255,255,255);
     selection-background-color:rgb(255,255,255);
     selection-color: green;
     selection-background-color: red;
'''

Normally you would use word boundaries ( \b ) to resolve this type of problem, however because your words can appear as part of a multi-part word with the parts separated by a hyphen (which matches a word boundary) this won't work.通常您会使用单词边界( \b )来解决此类问题,但是因为您的单词可以作为多部分单词的一部分出现,其中部分由连字符分隔(与单词边界匹配)这将不起作用. Instead, you can match with forward and backward negative lookarounds for a character or a hyphen around the word:相反,您可以为字符或单词周围的连字符匹配向前和向后的否定环视:

import re

css = '''
     selection-background-color: primary;
     selection-background-color:primary;
     selection-color: text-primary;
     selection-background-color: primary-text;
'''

css = re.sub(r'(?<![a-z-])primary(?![a-z-])', 'rgb(255,255,255)', css)
css = re.sub(r'(?<![a-z-])primary-text(?![a-z-])', 'red', css)
css = re.sub(r'(?<![a-z-])text-primary(?![a-z-])', 'green', css)
        
print(css)

Output: Output:

selection-background-color: rgb(255,255,255);
selection-background-color:rgb(255,255,255);
selection-color: green;
selection-background-color: red;

You can also try a dictionary-based approach, making a regex out of the keys of the dictionary and replacing with the matching value:您还可以尝试基于字典的方法,从字典的键中生成正则表达式并替换为匹配的值:

replacements = {
    'primary' : 'rgb(255,255,255)',
    'primary-text' : 'red',
    'text-primary' : 'green'
}
regex = '(?<![a-z-])(?:' + '|'.join(replacements.keys()) + ')(?![a-z-])'

css = re.sub(regex, lambda m: replacements[m.group()], css)

print(css)

Since all your replacements are on values in colon-delimited key-value pairs, you can instead use a dict that maps values to their replacements and use re.sub with a regex that groups the values and the characters before them to replace the matches with a function that returns the values replaced by the mapped replacements if they are in the mapping table:由于您的所有替换都在以冒号分隔的键值对中的值上,因此您可以改用将值映射到其替换的 dict 并使用re.sub和正则表达式,将值和它们之前的字符分组以替换匹配项一个 function 如果它们在映射表中,则返回被映射替换替换的值:

mapping = {
    'primary': 'rgb(255,255,255)',
    'primary-text': 'red',
    'text-primary': 'green'
}
css = re.sub(
    r'(:\s*)(.*);',
    lambda m: m.group(1) + mapping.get(m.group(2), m.group(2)),
    css
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM