如何使用某些形容词查找/替换独立单词或单词?

时间:2015-01-24 14:42:52

标签: python regex

  

德国苹果很好。 Apple很好。苹果在哪里?英国苹果   有蠕虫。英国人很好。

如果我有上述示例,我想将所有Appleapple替换为German apple。在上面的示例中,German apple应该被忽略,因为它已经是正确的。只有一个例外,如果有English apple,那么它仍应替换为German apple

使用在线regex generators,我想出了这个:

以下似乎允许我选择所有苹果(全球,多线) 但这也选择German apple,我应该禁止。

/\b(apple)/igm

这种尝试也不起作用。它只选择apple?

/\b(apple)[^German apple]/igm

我已经被困在这里了。不胜感激。

更新

正如here所解释的那样,我正在看正面和负面的外观。

如果我在上面的示例中添加了另一行:

  

荷兰人的苹果很酸。

我想跟Apple from Dutch一样说忽略German apple。 怎么能实现这一目标?

我没有运气就试过了:

(?i)(?:English )?(?:(?<!German )\bapple\b(?<! from dutch))

1 个答案:

答案 0 :(得分:2)

使用以下正则表达式,然后将匹配替换为German apple

(?<!German )(?:English )?\bapple\b

DEMO

OR

(?i)(?:English )?(?:(?<!German )\bapple\b)
  • (?i)不区分大小写的修饰符。
  • (?:English )?匹配可选的English字符串。
  • (?:(?<!German )\bapple\b)仅当apple字符串前面没有German时,才匹配它们。 (?<!German )负面的后视断言我们要匹配的字符串不会在字符串前面,而字符串与负面的lookbehind内部存在的模式相匹配。

DEMO

示例:

>>> string = 'German apple is good. Apple is nice. Where is the apple? English apple have worms. English people are nice.'
>>> re.sub(r'(?i)(?:English )?(?:(?<!German )\bapple\b)', r'German apple', string)
'German apple is good. German apple is nice. Where is the German apple? German apple have worms. English people are nice.'

<强>更新

(?i)(?:English )?(?:(?<!German )\bapple\b)(?!\s+from\s+Dutch\b)

DEMO