Python regex search until specific word and exclude everything behind it

Viewed 108

I have a script that always have the "get the" and the "get" in a string. The "ONE TWO THREE" can vary, like it also can be "THIRTEEN FORTY" or "SIX". After these variations there will always be a 2nd "get".

I have the following code:

variable = 'get the ONE TWO THREE get FOUR FIVE'

myVariable = re.compile(r'(?<=get the) .*')
myVariableSearch = myVariable.search(variable)
mySearchGroup = myVariableSearch.group()
print(mySearchGroup) 

#prints ONE TWO THREE get FOUR FIVE

I want my script to exclude the 2nd "get" and everything behind it. My desired result is to be just the "ONE TWO THREE".

How do I exclude this? Any help would be appreciated!

1 Answers

You can use

\bget\s+the\s+(.*?)(?=\s*\bget\b|$)

See the regex demo.

Details

  • \bget\s+the\s+ - whole word get, 1+ whitespaces, the, 1+ whitespaces
  • (.*?) - Group 1:
  • (?=\s*\bget\b|$) - a positive lookahead that requires 0+ whitespaces and then a whole word get, or end of string immediately on the right of the current location.

See the Python demo:

import re
variable = 'get the ONE TWO THREE get FOUR FIVE'
myVariableSearch = re.search(r'\bget\s+the\s+(.*?)(?=\s*\bget\b|$)', variable)
mySearchGroup = ''
if myVariableSearch:
    mySearchGroup = myVariableSearch.group(1)
print(mySearchGroup) 
# => ONE TWO THREE
Related