Search in a string and obtain the 2 words before and after the match in Python

后端 未结 4 2070
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 15:39

I\'m using Python to search some words (also multi-token) in a description (string).

To do that I\'m using a regex like this

    result = re.search(w         


        
4条回答
  •  野性不改
    2021-01-19 16:35

    I would do it like this (edit: added anchors to cover most cases):

    (\S+\s+|^)(\S+\s+|)here is(\s+\S+|)(\s+\S+|$)
    

    Like this you will always have 4 groups (might have to be trimmed) with the following behavior:

    1. If group 1 is empty, there was no word before (group 2 is empty too)
    2. If group 2 is empty, there was only one word before (group 1)
    3. If group 1 and 2 are not empty, they are the words before in order
    4. If group 3 is empty, there was no word after
    5. If group 4 is empty, there was only one word after
    6. If group 3 and 4 are not empty, they are the words after in order

    Corrected demo link

提交回复
热议问题