1

How can I get the content between two substrings? For example in "Hello, I have a very expensive car" I want to find the content between "Hello, I have" and "car", no matter what it is. How can I find the substring between the two strings?

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46

4 Answers4

0

You can try this:-

s = 'Hello, I have a very expensive car'
s = s.split(' ')

print(' '.join(s[s.index('have')+1:s.index('car')]))

Output:-

'a very expensive'
Dhaval Taunk
  • 1,662
  • 1
  • 9
  • 17
0

Regular expressions to the rescue:

import re

text = "Hello, I have a very expensive car"

pattern = re.compile(r'(?P<start>Hello, I have)(?P<middle>.+?)(?P<end>car)')

match = pattern.search(text)
if match:
    print(match.group('start'))
    print(match.group('middle'))
    print(match.group('end'))

Which yields (the spaces are intended):

Hello, I have
 a very expensive 
car

See a demo on regex101.com.


To have a variable text, you could make use of f-strings as in:
myVariable = "Hello, I have"
pattern = re.compile(rf'(?P<start>{myVariable})(?P<middle>.+?)(?P<end>car)')
Jan
  • 42,290
  • 8
  • 54
  • 79
0

try 're' module of Python for regular expressions:

import re

my_string = 'Hello, I have a very expensive car'
res = re.search('Hello, I have(.*)car', my_string)
print(res.group(1))
Roy Levy
  • 640
  • 1
  • 11
  • 24
-1

You could just remove the 2 strings in case there is no other text around

value = "Hello, I have a very expensive car"
res = re.sub("(Hello, I have|car)", "", value).strip()
print(res) # a very expensive
azro
  • 53,056
  • 7
  • 34
  • 70