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
  • 12,145
  • 3
  • 19
  • 36

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,634
  • 1
  • 8
  • 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
  • 40,932
  • 8
  • 45
  • 77
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
  • 532
  • 7
  • 22
-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
  • 47,041
  • 7
  • 30
  • 65