Regex for existence of some words whose order doesn't matter

前端 未结 2 2077
余生分开走
余生分开走 2020-11-27 05:16

I would like to write a regex for searching for the existence of some words, but their order of appearance doesn\'t matter.

For example, search for \"Tim\" and \"st

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 06:06

    You can use Positive Lookahead to achieve this. The lookahead approach is nice for matching strings that contain both substrings regardless of order.

    pattern = re.compile(r'^(?=.*Tim)(?=.*stupid).*$')
    

    Example:

    >>> s = '''Hey there stupid, hey there Tim
    Hi Tim, this is stupid
    Hi Tim, this is great'''
    ...
    >>> import re
    >>> pattern = re.compile(r'^(?=.*Tim)(?=.*stupid).*$', re.M)
    >>> pattern.findall(s)
    
    # ['Hey there stupid, hey there Tim', 'Hi Tim, this is stupid']
    

提交回复
热议问题