This Python program includes three new methods: between, before and after. We internally call find() and rfind(). These methods return -1 when nothing is found.
def between(value, a, b):
# Find and validate before-part.
pos_a = value.find(a)
if pos_a == -1: return
""
# Find and validate after part.
pos_b = value.rfind(b)
if pos_b == -1: return
""
# Return middle part.
adjusted_pos_a = pos_a + len(a)
if adjusted_pos_a >= pos_b: return
""
return value[adjusted_pos_a:pos_b]
def before(value, a):
# Find first part and return slice before it.
pos_a = value.find(a)
if pos_a == -1: return
""
return value[0:pos_a]
def after(value, a):
# Find and validate first part.
pos_a = value.rfind(a)
if pos_a == -1: return
""
# Returns chars after the found string.
adjusted_pos_a = pos_a + len(a)
if adjusted_pos_a >= len(value): return
""
return value[adjusted_pos_a:]
# Test the methods with this literal.
test =
"DEFINE:A=TWO"
print(between(test,
"DEFINE:",
"="))
print(between(test,
":",
"="))
print(before(test,
":"))
print(before(test,
"="))
print(after(test,
":"))
print(after(test,
"DEFINE:"))
print(after(test,
"="))
A
A
DEFINE
DEFINE:A
A=TWO
A=TWO
TWO