1
r = r'(?!.*66)get.*on'
txt = "get your kicks on Route 66"
res = re.search(r, txt)

I only want res=None if the exclusion text "66" would be included in the result text i.e. between "get" and "on". In this case it's outside the resulting text so I want to see a result but instead it's checking if "66" is anywhere in the whole text and returns res=None. Is there a way to do what I'm trying to do?

Tokyo D
  • 173
  • 2
  • 10
  • You call that "lookahead"? I think what's in your code should be called "lookbehind" – iBug Jan 29 '18 at 12:23

1 Answers1

1

To match a string between two strings excluding a third string, you can use a tempered greedy token (see more details about this construct at rexegg.com):

r = r'get(?:(?!66).)*on'
txt = "get your kicks on Route 66"
res = re.search(r, txt)

Here, (?:(?!66).)* matches any char (other than a line break char if re.DOTALL is not specified), 0 or more repetitions/consecutive occurrences, that does not start a 66 char sequence.

See the regex demo.

Note that you might want to tune it to get the shortest substring using r'get(?:(?!get|66).)*?on' expression.

See an updated regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563