Python regular expression match multiple words anywhere

前端 未结 2 1452
星月不相逢
星月不相逢 2020-12-17 21:53

I\'m trying to use python\'s regular expression to match a string with several words. For example, the string is \"These are oranges and apples and pears, but not pinapples

2条回答
  •  既然无缘
    2020-12-17 22:25

    Try this:

    >>> re.findall(r"\band\b|\bor\b|\bnot\b", "These are oranges and apples and pears, but not pinapples or ..")
    ['and', 'and', 'not', 'or']
    

    a|b means match either a or b

    \b represents a word boundary

    re.findall(pattern, string) returns an array of all instances of pattern in string

提交回复
热议问题